.NET CORE 2 EF Include

I use the new .net and EF core.

I need help with linq team. I have several 1: N models, and if the contais collection has some data marked as deleted, I don’t want to include it.

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 a condition

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

This does not work. How to write it down?

Now I have an IDeletable Interface, and it would be better if I had some kind of custom linq expression and could do for ex.

.Include(z => z.WorkPlaces).GetNonDeleted()

Does anyone know how to do this? I tried 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.

+4
source share
2 answers

You can configure the Request Filter in your DbContext.

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

gotta do the trick

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

+5

, Any Where, :

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

Source: https://habr.com/ru/post/1689705/


All Articles