简体   繁体   中英

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

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, Eg '(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM