【问题标题】:Why when I use GroupBy() in my LINQ to Entities query, the navigation property in the result is null?为什么当我在 LINQ to Entities 查询中使用 GroupBy() 时,结果中的导航属性为空?
【发布时间】:2013-07-08 08:59:34
【问题描述】:

已编辑:

我首先使用 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;
        }
}

这也是我的实体之间的关系:

但是当这个方法运行时,结果中包含的属性(DocumentStation)是null。我的错在哪里?

更新:

我测试过,如果我删除.GroupBy(),它会保留导航属性! 那么我该如何解决这个问题呢?

【问题讨论】:

  • 你不需要 .All()
  • @SamLeach: 我需要 .All() 因为我想用一个标准过滤所有记录
  • 默认过滤所有记录。
  • 它将使用我的标准过滤所有 DocumentStationHistory 记录,我想要这个。我返回的记录没问题,但导航属性为空。
  • 能否也显示一下 DocumentStationHistory 和 AppUser 关系的配置

标签: c# dictionary group-by linq-to-entities ef-code-first


【解决方案1】:

也有这个问题。我通过在 group by 之前执行 .ToList() 解决了这个问题。所以它会是:

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());

【讨论】:

  • 但是这个原因,先从Database加载所有数据,再从Group加载,这会影响性能。
  • 您应该使用.AsEnumerable 而不是.ToList。它流式传输前面的结果,而不是填充一个充满数据的列表。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-20
  • 2020-06-18
  • 2019-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多