2012-03-30 40 views
3

我试图写一个单一的查询,其中将包括的两个条件之一,基于输入变量:重新使用基于布尔值LINQ查询

!(from o in db.Products.Where(x => x.Company_ID == cid && x.IsDeleted != true) 

(from o in db.Products.Where(x => x.Company_ID == cid && x.IsDeleted != true) 

我现在的方法,覆盖前一个条件,如下所示。我已经包含productExists,它将成为决定我是否希望从上面获得条件#1或#2的参数。

public IQueryable<ProductImportViewModel> AllImports(int id, bool productExists) 
{ 
    return (from t1 in db.Products_Staging 
      where (t1.ImportFileId == id) && !(from o in db.Products.Where(x => x.Company_ID == cid && x.IsDeleted != true) 
               select o.ProductName).Contains(t1.ProductName) 
      select new ProductImportViewModel 
      { 
       Id = t1.Id 
      } 
} 

如果有人能帮助我,我会非常感激。

回答

2

事情是这样的,也许:

where (t1.ImportFileId == id) && 
      (
       productExists==true 
       && 
       !(from o in db.Products.Where(x => x.Company_ID == cid && x.IsDeleted != true). 
               Select(o=> o.ProductName).Contains(t1.ProductName) 
      ) 
      || 
      (
       productExists==false 
       && 
       (from o in db.Products.Where(x => x.Company_ID == cid && x.IsDeleted != true). 
               Select(o=> o.ProductName).Contains(t1.ProductName) 
      ) 

你也可以做这样的事情:

var query=(from o in db.Products 
      .Where(x => x.Company_ID == cid && x.IsDeleted != true). 
      Select(o=> o.ProductName); 
------ 
where (t1.ImportFileId == id) && 
    (
     productExists && !query.Contains(t1.ProductName) 
    ) 
    || 
    (
     !productExists && query.Contains(t1.ProductName) 
    ) 

两个查询会导致在同一个SQL

+0

感谢。这几乎是我所做的。我只是想知道是否有一个更简洁的方法来做到这一点! – Nick 2012-03-30 11:00:46

+0

更新了答案 – Arion 2012-03-30 11:07:49