Home > Blockchain >  Filter List of a model using linq
Filter List of a model using linq

Time:04-23

I have a Model with List inside it, is there any way to filter that list?

What I'm trying is:

List<Booking> a = await _context.Set<Booking>().Include(u => u.BookingLine).Include(u => u.BookingStatus).ToListAsync();

Inside that Booking model, there is a List. I just want to get all the StatusId = 1 inside that BookingStatus.

Booking model and BookingStatus model has the same BookingId. I don't know where do I put the Where() inside that linq.

I tried like this but it returned an error:

_context.Set<Booking>().Include(u => u.BookingLine).Include(u => u.BookingStatus
                        .LastOrDefault(a => a.StatusId == 1 || a.StatusId == 7 || a.StatusId == 13)).ToListAsync();    

Error:

System.InvalidOperationException: The expression 'u.BookingStatus.AsQueryable().LastOrDefault(a => (((a.StatusId == 1) OrElse (a.StatusId == 7)) OrElse (a.StatusId == 13)))' is invalid inside an 'Include' operation, since it does not represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, use casting ('t => ((Derived)t).MyProperty') or the 'as' operator ('t => (t as Derived).MyProperty'). Collection navigation access can be filtered by composing Where, OrderBy(Descending), ThenBy(Descending), Skip or Take operations. For more information on including related data

CodePudding user response:

I think you meant to use "Where" instead of "LastOrDefault".

something like:

_context.Set<Booking>().Include(u => u.BookingLine).Include(u => u.BookingStatus
                    .Where(a => a.StatusId == 1 || a.StatusId == 7 || a.StatusId == 13)).ToListAsync();

Microsoft example of Eager Loading:

using (var context = new BloggingContext())
{
    var filteredBlogs = context.Blogs
        .Include(
            blog => blog.Posts
               .Where(post => post.BlogId == 1)
               .OrderByDescending(post => post.Title)
               .Take(5))
        .ToList();
}
  • Related