Entity Framework v2.1.3: Order property (list of objects) of object

asp.net-core-2.1 c# entity-framework-core

Question

Poorly worded title, I know.

I have an object User that has an property (a list of objects) (ICollection<Alert>) Alerts. I want to order the alerts by the Alert's property (DateTime) LastActivatedDt

I tried (within a method w/ a parameter of int id):

user = users
    .Include(user => user.Alerts.OrderBy(alert => alert.LastActivatedDt)
    .FirstOrDefault(user => user.Id === id)

But I get the following error:

System.InvalidOperationException: The Include property lambda expression 'user => {from Alert alert in user.Alerts orderby [alert].LastActivatedDt asc select [alert]}' 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'.

1
0
9/11/2018 2:35:26 PM

Accepted Answer

You can't do that inside the include, and actually you don't need the include at all for this specific purpose. Just do:

users.OrderBy(o => o.Alerts.Min(a => a.LastActivatedDt)).FirstOrDefault();

You could use Max as well. It depends on how you ultimately want them ordered, but since you're dealing with a collection of things, you have to pick one out to actually order by.

EDIT

For some reason, I totally spaced out on the getting the user by a particular id part. I suppose what you're actually trying to achieve is to pull out a specific user, while having their collection of alerts ordered appropriately. That's not actually possible. What you'll have to do is something along the lines of:

var user = users.Include(x => x.Alerts).SingleOrDefault(x => x.Id == id);
var alerts = user.Alerts.OrderBy(o => o.LastActivatedDt);

You cannot order the user's alerts in place. You'll have to set some other variable with the result of the ordering.

3
9/11/2018 5:40:16 PM


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