嵌套集合中的OrderByDescending在EF 2.1查询中失败

时间:2018-09-09 03:17:39

标签: asp.net entity-framework asp.net-core entity-framework-core

此EF 2.1查询出现问题:

        return await _context.CorrespondenceItems
        .Include(x => x.Statuses.OrderByDescending(y => y.Date))
        .OrderByDescending(x => x.DateCreated)
        .ToListAsync();

问题是Statuss集合的OrderByDescending。我收到的错误是:

System.InvalidOperationException: The Include property lambda expression 'x => {from CorrespondenceItemStatus y in x.Statuses orderby [y].Date desc select [y]}' is invalid. The expression should represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, specify an explicitly typed lambda parameter of the target type, E.g. '(Derived d) => d.MyProperty'

这是我的(简化)模型:

public class CorrespondenceItem
{
    [Key]
    public int CorrespondenceItemId { get; set; }

    public virtual List<CorrespondenceItemStatus> Statuses { get; set; 
}

public class CorrespondenceItemStatus
{

    [Key]
    public int CorrespondenceItemStatusId { get; set; }

    public int CorrespondenceItem_CorrespondenceItemId { get; set; }

    [ForeignKey("CorrespondenceItem_CorrespondenceItemId")]
    public virtual CorrespondenceItem CorrespondenceItem { get; set; }

    public DateTime Date { get; set; }

}

更新:为了清楚起见,我希望按日期顺序降序收集CorrespondenceItems,并且其状态也按日期降序

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

            var result = await _db.CorrespondenceItem
            .Include(i => i.Statuses)
            .Select(r => new CorrespondenceItem
            {
                CorrespondenceItemId = r.CorrespondenceItemId,
                DateCreated = r.DateCreated,
                Statuses = r.Statuses.OrderByDescending(s => s.Date).ToList()
            })
            .OrderByDescending(i => i.DateCreated)
            .ToListAsync();