开发者

EF & Razor Keeping Unused Columns Off the Wire

I'm working on a page using ASP.NET MVC3, Razor and Entity Framework. I used nuget to grab mini-profiler and I'm noticing that the SQL calls are querying for all columns. I realize that this i开发者_运维问答s happening because I'm using the scaffold'ed views with IEnumerable, so my controller is returning View(Type.ToList()).

My knee jerk reaction is whip up some linq to select only the columns I need and put those into a list, but then I'd lose my "strong" EF types and their goodies like navigation properties.

Is it possible to instruct EF to only bring back data for a certain subset of the columns of the table being queried?


You could change it to leave the list as IQueryable (just remove the .ToList()), and select within your view. Because execution of the SQL query is deferred until you enumerate the results, any filter you add within the view will refine the query. Depending on how you look at it, that kind of messes with the separation of concerns though.

Your view code would become:

@model IQueryable<SomeType>
<ul>
@for(var item in Model.Select(x => new { x.Property1, x.Property2 })) {
    <li>@item.Property1</li>
}
</ul>

If you were to take this approach, you'd need to be pretty careful in your view to make sure you didn't enumerate the IQueryable more than once (thereby making extra database queries and negating any performance benefit).

The safest route would be to create a custom view model per view and project into that, but that's not really answering your question.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜