0

在我最近的应用程序中,我有一个Document实体,这个文档可以从一个用户引用到另一个用户,每组用户也有一个DocumentStation; 这些是指登录DocumentStationHistory表: 在此处输入图像描述

DocumentStationHistory现在,我想列出所有最后一个文档,首先将表中的日志引用到Dictionary使用 EF 代码(按分组documentId)。所以我写了这些方法:

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. 我的错误在哪里?

4

1 回答 1

2

订购的两个问题:

  • 您使用OrderBy了两次,几乎可以肯定它不会像您认为的那样做。您通常应该使用OrderBy后跟ThenBy
  • 我不相信GroupBy可以保证保持序列其余部分的顺序。您应该分组内订购:

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

(没有必要使用LastOrDefault-必须至少有一个元素,否则不会有一个组。

顺便说一句,使用的替代方法Last是使用OrderByDescendingand ThenByDescending,然后使用First

DocumentStation恐怕我不知道包含部分。

于 2013-07-08T10:55:11.230 回答