开发者

ASP.NET MVC & Entity Framework: How to render a custom Model in a View?

I have two tables Category 1..* Advertisement.

I want to get the advertisements Count for each category. To do so, I use that开发者_开发知识库 query:

var catList = (from c in DB.Category.Include("Advertisement")
                  select new { c.Name, c.Advertisement.Count }
                  ).ToList();

How to access the e.g the first element's property Name and Count via View ?


I'd use a view model, like:

var catList = (from c in DB.Category.Include("Advertisement")
                  select new CategorySummaryViewModel{ Name = c.Name, AdsCount = c.Advertisement.Count }
                  ).ToList();

Unrelated & not sure: but I think you can take out the .Include in that linq query / since you are getting a projection, not a Category instance that you want it's Advertisement property populated.


You will have to use a collection of a strongly typed object instead of using anonymous types.

Please see Dynamic typed ViewPage for an explanation, but the readers' digest version is that anonymous types are internal.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜