我遇到了 LinqKit 谓词生成器的问题。我过去曾将它用于简单查询,它运行良好,但我现在尝试将它与语句中的 Any 子句一起使用,它似乎给了我随机结果。下面是我用来构建语句的代码。谁能看到我做错了什么?有没有更好更简单的方法来做我想做的事。我现在正在使用谓词构建器,因为我正在构建一个非常复杂的查询,它可能包含嵌套谓词等,而且我没有看到其他简单的方法可以做到这一点。我将它与实体框架一起使用。
if (cqv.ComplexQuery.IncludeOnAll)
{
Includepredicate = PredicateBuilder.True<Customer>();
}
else
{
Includepredicate = PredicateBuilder.False<Customer>();
}
inner = PredicateBuilder.True<Customer>();
if (a.Include == true || a.Exclude == true)
{
productinner = PredicateBuilder.True<CustomerProduct>();
if (a.VersiondID != 0)
{
productinner = productinner.And(o => o.ProductTypeID == a.ProductType.ID && o.VersionID == a.VersiondID);
inner = inner.And(o => o.Products.Any(productinner.Compile()));
}
else
{
productinner = productinner.And(o => o.ProductTypeID == a.ProductType.ID);
inner = inner.And(o => o.Products.Any(productinner.Compile()));
}
if (cqv.ComplexQuery.IncludeOnAll)
{
Includepredicate = Includepredicate.And(inner.Expand());
}
else
{
Includepredicate = Includepredicate.Or(inner.Expand());
}
}
IncludedCustomers = UoW.Customers.AsExpandable().Where(Includepredicate).ToList();
//This second list does the exact query the first one should be doing so I could compare results. The reuslts are totally different. Not only are there more results using predicatebuilder but they seem random
List<Customer> test = UoW.Customers.Where(o => o.Products.Any(s => s.ProductTypeID == 1)).ToList();
我也没有看到任何简单的方法来尝试使用谓词构建器来调试问题。有谁知道确定从此查询创建的 SQL 的快速方法?
编辑 - - - - - - - - - - - - - - - - - - - - - - -
所以我已经解决了我的部分问题,但遇到了另一个问题。Any 子句和随机结果的问题已通过我在带有 a.ProductType.ID 的整数变量中设置并在子句中使用该值来解决。一旦我这样做了,我就得到了我期望的结果。现在我的问题是,即使这适用于1个产品,当我选择Naymore而不是1,而不是要么寻找那些拥有这两个产品的任何客户,那么我GT总是只有客户我在 for 中添加了一个子句的最后一个产品。我将把我更新的代码放在下面
foreach (CustomerProductQueryProduct a in cqv.ComplexQuery.Products)
{
inner = PredicateBuilder.True<Customer>();
if (a.Include == true || a.Exclude == true)
{
value = a.ProductType.ID;
productinner = PredicateBuilder.True<CustomerProduct>();
if (a.VersiondID != 0)
{
productinner = productinner.And(s => s.ProductTypeID == value && s.VersionID == a.VersiondID);
inner = inner.And(o => o.Products.Any(productinner.Compile()));
}
else
{
productinner = productinner.And(s => s.ProductTypeID == value);
inner = inner.And(o => o.Products.Any(productinner.Compile()));
}
if (cqv.ComplexQuery.IncludeOnAll)
{
Includepredicate = Includepredicate.And(inner.Expand());
}
else
{
Includepredicate = Includepredicate.Or(inner.Expand());
}
}
}
IncludedCustomers = UoW.Customers.AsExpandable().Where(Includepredicate).ToList();
PredicateBuilder 不能处理多个 Any 子句吗?