Exclude deleted child when using EF core Include

asp.net-core entity-framework-core linq

Question

Here is my entity structure:

enter image description here
My code to get the Courses with all child Tests:

var course = await Db.Courses.Include(x => x.Tests).FirstOrDefaultAsync(y => y.CourseId == id);

It includes all the child Tests related to the Courses. But I want to include all Tests that status is not deleted (IsDeleted = false). To do that I have use this code:

var course = await Db.Courses.Include(x => x.Tests.Where(y=>!y.IsDeleted)).FirstOrDefaultAsync(y => y.CourseId == id);

But it doesn't exclude the deleted Tests. Can anybody tell me how I can exclude the deleted tests?

1
1
1/20/2020 4:00:50 AM

Accepted Answer

I got my solution. I solved it by adding a global filter like below:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.Entity<Test>().HasQueryFilter(p => !p.IsDeleted);
}

Details explanation here

1
1/20/2020 6:46:02 AM

Popular Answer

You could not do filter in Include in EF core, try to use below code instead

var course = await Db.Courses.Include(x => x.Tests).FirstOrDefaultAsync(y => y.CourseId == id);
course.Tests = course.Tests.Where(t => !t.IsDeleted).ToList();

Refer to Filtering on Include in EF Core



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow