EF LINQ'WHERE IN'同时有2个字段

时间:2014-01-18 03:23:35

标签: c# linq entity-framework

我有下表:

id             (bigint)  
adId           (bigint)  
listId         (bigint)  
listFieldValue (bigint)  

我有这个搜索列表:

List<long> searchListFieldValues = new List<long>();
searchListFieldValues.Add(100);
searchListFieldValues.Add(200);  

所以我用:

using (ClearWhiteDBEntities cwContext = new ClearWhiteDBEntities())
{ 
    var adsWithRelevantadFields =
      from adField in cwContext.tblAdFields
      join ads in cwContext.tblAds on adField.adId equals ads.id
      group adField by adField.adId into adAdFields
      where searchListFieldIds.All(i => adAdFields.Select(co => co.listFieldValue).Contains(i))
      select adAdFields.Key;

    MessageBox.Show(adsWithRelevantadFields.Count().ToString());
}

但现在我需要同时检查两个字段listIdlistFieldId,因此我创建了另一个搜索列表:

List<long> searchListIds = new List<long>();
searchListIds.Add(11);
searchListIds.Add(12); 

现在我需要让所有adId拥有(listId == 11 && listFieldValue==100)和(listId == 12 && listFieldValue==200

我试过了:

where searchListIds.All(i => adAdFields.Select(co => co.listId).Contains(i))
   && searchListFieldValues.All(i => adAdFields.Select(co => co.listFieldValue).Contains(i))  

但它不起作用。任何解决方案?

1 个答案:

答案 0 :(得分:0)

如何将where条目放在group之前?

var adsWithRelevantadFields =
  from adField in cwContext.tblAdFields
  join ads in cwContext.tblAds on adField.adId equals ads.id
  where ((adField.listId == 11 && adField.listFieldValue == 100)
         || (adField.listId == 12 && adField.listFieldValue == 200)
  group adField by adField.adId into adAdFields
  select adAdFields.Key;