如何在GroupBy中使用Include

时间:2015-02-07 19:08:25

标签: c# linq entity-framework

这是我模特的一部分:

public class Transaction
{
    public int Id { get; set; }
    public Decimal Amount { get; set; }
    public DateTime Date { get; set; }
    public string Comment { get; set; }
    public Subcategory TransactionSubcategory { get; set; }
    public Member OwnerMember { get; set; }
    public int TransactionSubcategoryId { get; set; }
    public int OwnerMemberId { get; set; }
}

public class Subcategory
{
    public Subcategory()
    {
        IsGlobal = false;
        Transactions = new List<Transaction>();
    }
    public int Id { get; set; }
    public string Name { get; set; }
    public Category OwnerCategory { get; set; }
    public List<Transaction> Transactions { get; set; }
    public bool IsGlobal { get; set; }
}

public class Category
{
    public Category()
    {
        IsGlobal = false;
    }
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Subcategory> Subcategories { get; set; }
    public TransactionType TypeOfTransaction { get; set; }
    public Budget OwnerBudget { get; set; }
    public bool IsGlobal { get; set; }
}

public class Member
{
    public Member()
    {
        Transactions = new List<Transaction>();
    }
    public Budget OwnerBudget { get; set; }
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime CreatedTime { get; set; }
    public List<Transaction> Transactions { get; set; }
}

在这种方法中,我尝试包含TransactionSubcategory.OwnerCategory

    private List<ReportMembers> GetMembersReport(IQueryable<Transaction> transactions)
    {
        var members = transactions
            .Include(t=> t.TransactionSubcategory.OwnerCategory)
            .GroupBy(t => t.OwnerMember, t => t)
            .ToList();
...
     }

但它仍然是空的。如果我改为

        var members = transactions
            .GroupBy(t => t.OwnerMember, t => t)
            .Include(t=> t.Select(t2 => t2.TransactionSubcategory.OwnerCategory))
            .ToList();

我得错了:

  

类型&#39; System.ArgumentException&#39;的例外情况发生在EntityFramework.dll中但未在用户代码中处理

     

附加信息:Include路径表达式必须引用在类型上定义的导航属性。使用虚线路径作为参考导航属性,使用Select运算符作为集合导航属性。

2 个答案:

答案 0 :(得分:0)

首先:从数据库中选择时应包括这些导航:

from o in context.Transactions.Include("TransactionSubcategory").Include("TransactionSubcategory.OwnerCategory")
...
select o

第二步:从此处删除包含

var members = transactions
            .GroupBy(t => t.OwnerMember, t => t)
            .ToList();

第三:我认为你想按ID而不是按类分组,因为按引用类型分组不会给你预期的结果。具有相同字段的所有类将生成不同的组,因为它们具有不同的引用。

var members = transactions
                .GroupBy(t => t.OwnerMember.Id, t => t)
                .ToList();

答案 1 :(得分:0)

我找到了解决方案。如果我首先制作ToList以及之后GroupBy,那么就可以了。

var members = transactions
            .Include(t => t.TransactionSubcategory.OwnerCategory)
            .Include(t=> t.OwnerMember).ToList()
            .GroupBy(t => t.OwnerMember, t => t)