שולמית שרשבסקי שולמית שרשבסקי - 4 months ago 39
C# Question

Entity Framework include items only by condition

I need my context to include the

sonns
by a condition, I need the rows that not deleted (logical delete).

I understood that I cannot add a condition to the include; so I want to filter the context, but it's not working.

var aa = ctx.aa
.Include(t => t.vari)
.ToList()
.FirstOrDefault();

ctx.vari.Where(bi => bi.ID == 10 && bi.Deleted == 1).ToList();


Thanks!

Answer

As codelahiru && hbulens pointed out, you missed the bi for ID.

Disclaimer: I'm the owner of the project Entity Framework Plus

The Query IncludeOptimized feature allows to filter with include and optimize the query performance at the same time (Support EF5, EF6)

var aa = ctx.aa
            .IncludeOptimized(t => t.vari.Where(bi => bi.ID == 10 && bi.Deleted == 1))
            .FirstOrDefault();

Documentation: EF+ Query IncludeOptimized