【问题标题】:Counting navigation property occurrence计数导航属性的出现
【发布时间】:2015-12-25 21:42:25
【问题描述】:

如果我有以下两个models:

public class Book
{
    public int ID { get; set; }
    public string Title { get; set; }
    //other properties
    public virtual Category Category { get; set; }
}


public class Category
{ 
    public int ID { get; set; }
    public string CategoryName { get; set; }
    public virtual ICollection<Book> Books { get; set; }
}

我正在向视图发送List&lt;Book&gt;

public class ShopController : Controller
{
    private BookStoreMDFEntities db = new BookStoreMDFEntities();
    public ActionResult Index()
    {
        var list = db.Books.Include("Category").ToList();
        return View(list);
    }
}

如何查看Book 列表中每个类别的类别名称和出现次数?
示例输出

  • 科学:2
  • 数学:4 ...

【问题讨论】:

    标签: c# asp.net-mvc entity-framework linq razor


    【解决方案1】:

    匿名类型方式

    如果您使用的是实体框架,您可以执行以下操作:

    var list = db.Category.Select(c => 
    new { 
        Name = c.CategoryName, 
        Count = c.Books.Count
    }).ToList();
    

    然后将其发送到您的视图并在 Razor 中使用 @foreach 进行渲染。

    列出场景

    如果您确实需要发送List&lt;Book&gt; 来查看,您可以在视图内分组书籍:

    @{
        var list = Model.GroupBy(b => b.Category.CategoryName);
    }
    @foreach (var entry in list)
    {
        <div>@entry.Key : @entry.Count()</div>
    }
    

    【讨论】:

    • 我的问题的目的是通过发送 Book 模型而不是 category 来实现这一点。基本上我打算这样做,因为我在将书籍发送到View 时对它们进行排序,但是如果我发送Category 模型,我将花费大量工作来对导航属性进行排序@987654328 @ 在其中,我也可以发送Category 模型并将每个类别的计数视为Model.Books.Count,因为书籍是类别中的ICollection&lt;Book&gt;。这也不会带来 100% 的成功,Books 将在它们的Category 中进行排序不是有效的排序
    • 我已经编辑了我的答案以满足您的要求。 下次请更准确;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 2016-09-01
    相关资源
    最近更新 更多