.NET CORE 2 EF Include

穿精又带淫゛_ 提交于 2019-12-19 18:29:21

问题


I am using new .net core and EF.

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.

How to do it?

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

If I add the condition

.Include(z => z.WorkPlaces).Where(x=>x.WorkPlaces.Where(x=>!x.IsDeleted))

It doesn't work. How to write this correctly?

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

Thanks guys.


回答1:


You can configure a Query Filter in your DbContext.

modelBuilder.Entity<Administrator>()
            .HasQueryFilter(admin => !EF.Property<boolean>(admin, "IsDeleted"));

should do the trick

Reference link: https://docs.microsoft.com/en-us/ef/core/querying/filters




回答2:


You should change the inner condition using Any instead of Where, as:

.Include(z => z.WorkPlaces)
.Where(x => x.WorkPlaces.Any(y => !y.IsDeleted))


来源:https://stackoverflow.com/questions/47440972/net-core-2-ef-include

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!