简体   繁体   中英

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.

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM