1

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?

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Arif
  • 6,094
  • 4
  • 49
  • 81

3 Answers3

5

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

Arif
  • 6,094
  • 4
  • 49
  • 81
  • 2
    But what if you want all records including those having IsDeleted = true? As per docs you linked, in such case you need to use `IgnoreQueryFilters()`. You should mark your own answer as accepted! +1 – Sнаđошƒаӽ Jan 20 '20 at 16:53
0

Regular include cannot work with filter. You need to download Z.EntityFramework.Plus.EFCore from nuget. And use code below

var course = await Db.Courses.Where(y => y.CourseId == id).IncludeFilter(x => x.Tests.Where(y => y.IsDeleted == false)).FirstOrDefaultAsync;
Asherguru
  • 1,687
  • 1
  • 5
  • 10
0

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

Ryan
  • 19,118
  • 10
  • 37
  • 53
  • This is a good solution, but it seems a little costly. I have added a solution by exploring documentation. – Arif Jan 20 '20 at 06:54