OrderByDescending in nested collection failing in EF 2.1 query

asp.net asp.net-core entity-framework entity-framework-core

Question

I'm having a problem with this EF 2.1 query:

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

The problems is the OrderByDescending for the Statuses collection. The error I'm getting is:

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'

This is my (simplified) model:

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; }

}

Update: To be clear, I would like an ordered by date descending collection of CorrespondenceItems with their Statuses ordered by date descending as well

1
0
9/9/2018 5:19:43 AM

Accepted Answer

Try Code below:

            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();
0
9/10/2018 5:35:59 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow