【问题标题】:ASP.NET MVC & Entity Framework: How to render a custom Model in a View?ASP.NET MVC 和实体框架:如何在视图中呈现自定义模型?
【发布时间】:2010-09-13 19:34:31
【问题描述】:

我有两张桌子类别 1..* 广告。

我想获取每个类别的广告计数。为此,我使用该查询:

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

如何通过 View 访问例如第一个元素的属性 Name 和 Count ?

【问题讨论】:

    标签: asp.net-mvc linq-to-sql entity-framework


    【解决方案1】:

    我会使用视图模型,例如:

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

    不相关且不确定:但我认为您可以在该 linq 查询中取出 .Include / 因为您获得的是投影,而不是您希望填充广告属性的 Category 实例。

    【讨论】:

      【解决方案2】:

      您将不得不使用强类型对象的集合,而不是使用匿名类型。

      请参阅Dynamic typed ViewPage 以获得解释,但读者的摘要版本是匿名类型是内部的。

      【讨论】:

        猜你喜欢
        • 2010-11-20
        • 2014-11-30
        • 1970-01-01
        • 1970-01-01
        • 2011-07-22
        • 1970-01-01
        • 1970-01-01
        • 2012-02-23
        • 1970-01-01
        相关资源
        最近更新 更多