开发者

MVC more specified models should be populated by more precise query too?

开发者 https://www.devze.com 2022-12-24 16:07 出处:网络
If you have a Car model with 20 or so properties开发者_JS百科 (and several table joins) for a carDetail page then your LINQ to SQL query will be quite large.

If you have a Car model with 20 or so properties开发者_JS百科 (and several table joins) for a carDetail page then your LINQ to SQL query will be quite large.

If you have a carListing page which uses under 5 properties (all from 1 table) then you use a CarSummary model. Should the CarSummary model be populated using the same query as the Car model?

Or should you use a separate LINQ to SQL query which would be more precise?

I am just thinking of performance but LINQ uses lazy loading anyway so I am wondering if this is an issue or not.


Create View Models to represent the different projections you require, and then use a select projection as follows.

from c in Cars
select new CarSummary
{
    Registration = c.Registration,
    ...
}

This will create a query that only select the properties needed.

relationships will be resolved if they are represented in the data context diagram (dbml)

select new CarSummary
{
     OwnerName = c.Owner.FirstName
}

Also you can nest objects inside the projection

select new CarSummary
{
     ...
     Owner = new OwnerSummary
     {
         OwnerName = c.Owner.FirstName, 
         OwnerAge = c.Owner.Age
     }
     ...
}

If you are using the same projection in many places, it man be helpful to write a method as follows, so that the projection happens in one place.

public IQueryable<CarSummary> CreateCarSummary(IQueryable<Car> cars)
{
    return from c in cars
           select new CarSummary
           {
               ...
           }
}

This can be used like this where required

public IQueryable<CarSummary> GetNewCars()
{
     var cars = from c in Cars
                select c;

     return CreateCarSummary(cars);

}


I think that in your case lazy loading doesn't bring much benefit as you are going to use 1 property from each table, so sooner or later to render the page you will have to perform all the joins. In my opinion you could use the same query and convert from a Car model to a CarSummary model.


If performance is actually a concern or an issue currently, you should do a separate projection linq query so that the sql query only selects the 5 fields you need to populate your view model instead of returning all 20 fields.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号