谓词在foreach循环中不起作用

时间:2018-08-17 08:48:26

标签: c#

 if (rowCount == 1)
    {
       query =
               (from x in partJoinTableRepository.GetPartJoinQuery()
                 join y in partRepository.GetPartsQuery() on x.PartId equals y.Id
                               join z in partProductTypeReposiotry.GetPartProductTypesQuery() on x.PartId equals z.PartId
                               where y.IsSkipped == 0 && (y.IsDisabled != "Y" || y.IsDisabled == null) && z.CreatedDate == x.CreatedDate
                               && x.CreatedDate == Convert.ToDateTime(fromDate) && cpaclassids.Contains(x.ProductTypeId.ToString())
                               select x).Cast<PartJoinTable>().AsQueryable();
                      predicate = PredicateBuilder.True(query);
   }
   else
   {   
    query = query.Join(partJoinTableRepository.GetPartJoinQuery(), "PartID", "PartID", "inner", "row1", null).Cast<PartJoinTable>().AsQueryable();
                        // predicate = PredicateBuilder.True(query);
   } //query contains multiple dynamic inner joins
       //repids contains the list ,I used the predicate builder for the linq to create AND Queries
   foreach(var item in repids)
   { 
      predicate = PredicateBuilder.True(query);
      if (typeid == "3")
      {
       predicate = predicate.And(z => ids.Contains(z.ProductTypeId.ToString()) && 
               z.CreatedDate == Convert.ToDateTime(fromDate));                            
      }
  }
var count = query.Where(predicate).Distinct().Count();

此处谓词未附加多个And条件。它占用了最后一个And条件,而另一个And条件被消除了。

1 个答案:

答案 0 :(得分:2)

您正在覆盖每个循环的谓词。

这应该有效

      predicate = PredicateBuilder.True(query);
foreach(var item in repids)
   { 

      if (typeid == "3")
      {
       predicate = predicate.And(z => ids.Contains(z.ProductTypeId.ToString()) && 
               z.CreatedDate == Convert.ToDateTime(fromDate));                            
      }