实体框架Linq包含where子句

时间:2017-09-26 16:43:51

标签: c# entity-framework linq

我有Audience Object和SocialAudience对象。受众可以拥有一个或多个SocialAudience和其他对象。

我想让那些有IsDeleted列= 0的SocialAudience的受众群体。

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

此代码的结果是具有IsDeleted = 0和= 1的socialAudiences的受众。

1 个答案:

答案 0 :(得分:1)

由于SocialAudiences是一对多,您需要指定是否需要Audience.IsDeleted == 0和所有SocialAudiences.IsDeleted == 0或者只有1的IsDeleted == 0.对于后者,请尝试:

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

如果您要求所有孩子都有IsDeleted == 0,请使用All()代替Any()