Zied CHAARI
Zied CHAARI

Reputation: 269

Entity Framework Linq include with where clause

I have Audience Object and SocialAudience object. Audience can have one or many SocialAudience and other objects.

I want to get Audiences with there SocialAudiences that have IsDeleted column = 0.

 var audience = await db.Audiences.Include(A => A.AudienceUsersSources)
                                             .Include("AudienceUsersSources.AudienceUsersSourceDetails")
                                             .Include("SocialAudiences.AdAccount")
                                             .Where(A => A.CustomerCode == CustomerCode
                                                         && A.IsDeleted == 0
                                                         ).OrderByDescending(A => A.ID).ToListAsync();

the result of this code is audiences with socialAudiences that have IsDeleted = 0 and = 1.

Upvotes: 1

Views: 629

Answers (1)

Steve Greene
Steve Greene

Reputation: 12304

Since SocialAudiences is one to many you need to specify if you want it where Audience.IsDeleted == 0 and all of the SocialAudiences.IsDeleted == 0 or if just 1 has IsDeleted == 0. For the latter, try:

var audience = await db.Audiences
                       .Include(a => a.AudienceUsersSources.AudienceUsersSourceDetails)
                       .Include(a => a.SocialAudiences.AdAccount)
                       .Where(a => a.CustomerCode == CustomerCode &&
                                   a.IsDeleted == 0 &&
                                   a.SocialAudiences.Any(sa => sa.IsDeleted == 0))
                       .OrderByDescending(A => A.ID)
                       .ToListAsync();

If you require all the children to have IsDeleted == 0, then use All() instead of Any().

Upvotes: 1

Related Questions