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'.
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.