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

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

已编辑:

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

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

enter image description here

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

更新:

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

最佳答案

也有这个问题。我通过在 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());

关于c# - 为什么当我在 LINQ to Entities 查询中使用 GroupBy() 时,结果中的导航属性为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17522598/

相关文章:

python - 访问嵌套字典列表中的值

php - 嵌套 while 循环不适用于我的 GROUP BY 查询

c# - 您如何为委托(delegate)参数提供 xml 注释/文档?

c# - 使用 iTextSharp 为 PDF 文档中的一段文本着色背景

python - 在 Python 中从一对或名称映射到一个值

Python:数据对象或类

c# - 在 WPF 代码中绑定(bind)路径和源

c# - 存储过程 EF 和 NET CORE

带有分组依据的 jQuery 表插件

mysql - GROUP BY 具有时移的日期时间