.NET CORE 2 EF包括
我正在使用新的.net核心和EF.
I am using new .net core and EF.
我需要包含linq命令的帮助.我有一些1:N模型,如果集合包含一些标记为已删除"的数据,我不想包含它们.
I need help with include linq command. I have some 1:N models and if the collection contais some data marked like deleted I do not want to include them.
该怎么做?
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))
它不起作用.如何正确编写呢?
It doesn't work. How to write this correctly?
接下来的事情是我有IDeletable接口,如果我有一些自定义linq表达式并且可以用于ex会更好.
Next thing is I have IDeletable Interface and it would be better if I had some custom linq expression and could do for ex.
.Include(z => z.WorkPlaces).GetNonDeleted()
有人知道怎么做吗? 我尝试过这样的事情
Does anyone know how to do it? I tryed something like this
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中配置查询过滤器.
You can configure a Query Filter in your DbContext.
modelBuilder.Entity<Administrator>()
.HasQueryFilter(admin => !EF.Property<boolean>(admin, "IsDeleted"));
应该可以解决问题
参考链接: https://docs.microsoft.com/zh-cn/ef/core/querying/filters