简体   繁体   English

为什么当我在LINQ to Entities查询中使用GroupBy()时,结果中的导航属性为null?

[英]Why when I use GroupBy() in my LINQ to Entities query, the navigation property in the result is null?

Edited: 编辑:

I'm developing an application with EF code first, I have a method that return a Dictionary<int,T> : 我首先用EF代码开发一个应用程序,我有一个返回Dictionary<int,T>

public Dictionary<int, DocumentStationHistory> GetLastDocumentStationHistoryListOfDocuments(string criteria)
{
        Dictionary<int, DocumentStationHistory> result = new Dictionary<int, DocumentStationHistory>();
        using (IUnitOfWork uow = new MyContext())
        {
            DocumentStationHistoryRepository repository = new DocumentStationHistoryRepository(uow);
            result = repository.All().
                Include(x => x.DocumentStation).
                Where(criteria,new object[]{}).
                OrderBy(d=>d.DocumentId).
                OrderBy(d=>d.DocumentStationHistoryId).
                GroupBy(g => (int)g.DocumentId).
                ToDictionary(g => (int)g.Key, g => g.LastOrDefault());
            return result;
        }
}

Also it's the relation between my entities: 这也是我的实体之间的关系:

在此输入图像描述

But when this method runs, the included property( DocumentStation ) in the result is null . 但是当此方法运行时,结果中包含的属性( DocumentStation )为null where is my mistake? 我的错在哪里?

Updated: 更新:

I tested that if I remove the .GroupBy() , it keeps the navigation property! 我测试了如果我删除.GroupBy() ,它保留了导航属性! So how can I solve this problem? 那么我该如何解决这个问题呢?

Also had this issue. 也有这个问题。 I solved it by doing a .ToList() before the group by. 我通过在group by之前执行.ToList()来解决它。 So it would be: 所以它会是:

result = repository.All().
         Include(x => x.DocumentStation).
         Where(criteria,new object[]{}).
         OrderBy(d=>d.DocumentId).
         OrderBy(d=>d.DocumentStationHistoryId).
         ToList().
         GroupBy(g => (int)g.DocumentId).
         ToDictionary(g => (int)g.Key, g => g.LastOrDefault());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM