使用 linq 过滤模型列表

Filter List of a model using linq

我有一个模型,其中包含列表,有什么方法可以过滤该列表吗?

我正在尝试的是:

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

在预订模型中,有一个列表。我只想获取 BookingStatus 中的所有 StatusId = 1。

预订模型和 BookingStatus 模型具有相同的 BookingId。我不知道我应该把 Where() 放在那个 linq 的什么地方。

我这样试过,但返回错误:

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

错误:

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

我想你是想用“Where”而不是“LastOrDefault”。

类似于:

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

Eager Loading 的 Microsoft 示例:

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