c# - 基于 bool 值重新使用 LINQ 查询

标签 c# linq entity-framework linq-to-sql

我正在尝试编写一个查询,其中将包含基于输入变量的两个条件之一:

!(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
            }
}

如果有人能帮我解决这个问题,我将不胜感激。

最佳答案

可能是这样的:

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

关于c# - 基于 bool 值重新使用 LINQ 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9941581/

相关文章:

c# - 如何使用 LinqToTwitter 获取标签上的所有推文

c# - 使用包含的 Linq 查询不起作用

c# - EF 枚举所有被忽略的属性

c# - 仅在填充后重新排序 TreeView 节点 [0]

c# - 分号在 C# 中的条件 block 之后做什么?

c# - 帮助 LINQ 查询

c# - 将多个导航属性配置到同一个表时出错

c# - Entity Framework 6 事务回滚

c# - 底层连接已用linkedin关闭

c# - 以 XML 形式存储的查询字符串属性