[英].NET CORE 2 EF Include
我正在使用新的.net核心和EF。
我需要幫助包括linq命令。 我有一些1:N模型,如果集合包含一些標記為已刪除的數據,我不想包含它們。
怎么做?
var company = await _context.Company
.Include(y => y.Administrators)
.Include(y => y.CompanyPartTimers)
.Include(z => z.WorkPlaces)
.Include(z => z.Requirements)
.FirstAsync(x => x.Id == id);
如果我添加條件
.Include(z => z.WorkPlaces).Where(x=>x.WorkPlaces.Where(x=>!x.IsDeleted))
它不起作用。 如何正確寫?
接下來的事情是我有IDeletable接口,如果我有一些自定義的linq表達式並且可以為ex做的話會更好。
.Include(z => z.WorkPlaces).GetNonDeleted()
有誰知道怎么做? 我嘗試過這樣的事情
public static class LinqExtension
{
public static IEnumerable<T> GetActive<T>(this IEnumerable<T> source) where T : class, IDeletable
{
return source.Where(x => x.IsDeleted);
}
}
多謝你們。
您可以在DbContext中配置查詢過濾器 。
modelBuilder.Entity<Administrator>()
.HasQueryFilter(admin => !EF.Property<boolean>(admin, "IsDeleted"));
應該做的伎倆
參考鏈接: https : //docs.microsoft.com/en-us/ef/core/querying/filters
您應該使用Any
而不是Where
來更改內部條件,如下所示:
.Include(z => z.WorkPlaces)
.Where(x => x.WorkPlaces.Any(y => !y.IsDeleted))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.