我有下面的LINQ查询,它应该查看表Products,并向我返回传递的参数的记录,这些记录是:一个搜索项(字符串)和不同"类型"的3个布尔值。
var query = context.Products
.Where(a => request.SearchTerm == null || a.Name.Contains(request.SearchTerm))
.Where(a => (request.isTypeA == false || (a.OrderType == "X" && request.isTypeA == true)) ||
(request.typeB == false || (a.OrderType == "R" && request.typeB == true))
|| (request.typeC == false || (a.OrderType == "D" && request.typeC == true)))
.Where (a=> a.OrderType != "U")
.Where(a => a.IsInactiveFlag == false )
.OrderBy(a => a.OrderType)
.Select(c => new ProductType
{
ProductTypeId = c.ProductTypeId,
IsSelected = false,
OrderType = c.OrderType,
Name = c.Name,
IsInactiveFlag = c.IsInactiveFlag
});
问题:问题是查询总是通过查看传递的searchTerm来返回记录,但没有考虑布尔参数。比如说,我的搜索参数是:searchTerm="reference",isTypeA=false,isTypeB=false和isTypeC=true。上述查询将返回所有不同类型的searchTerm"reference"的所有记录,而不仅仅是TypeC。
在发布这个问题之前,我在谷歌上搜索了很多,但没有什么是我遇到的。请告诉我我做错了什么。谢谢
试试这个
var query = context.Products
.Where(a => request.SearchTerm == null || a.Name.Contains(request.SearchTerm))
.Where(a => (a.OrderType == "X" && request.isTypeA)
|| (a.OrderType == "R" && request.typeB)
|| (a.OrderType == "D" && request.typeC))
.Where (a=> a.OrderType != "U")
.Where(a => a.IsInactiveFlag == false )
.OrderBy(a => a.OrderType)
.Select(c => new ProductType
{
ProductTypeId = c.ProductTypeId,
IsSelected = false,
OrderType = c.OrderType,
Name = c.Name,
IsInactiveFlag = c.IsInactiveFlag
});
您应该在过滤器值的每个测试旁边显式显示OrderType的包含/排除二进制标准,它可以作为开关。。。。
var query = context.Products
.Where(a => request.SearchTerm == null || a.Name.Contains(request.SearchTerm))
.Where(a => (request.isTypeA == false && a.OrderType != "X" ) || (a.OrderType == "X" && request.isTypeA == true)) ||
(request.typeB == false && a.OrderType != "R" )|| (a.OrderType == "R" && request.typeB == true))
|| (request.typeC == false && a.OrderType != "D" ) || (a.OrderType == "D" && request.typeC == true)))
.Where (a=> a.OrderType != "U")
.Where(a => a.IsInactiveFlag == false )
.OrderBy(a => a.OrderType)
.Select(c => new ProductType
{
ProductTypeId = c.ProductTypeId,
IsSelected = false,
OrderType = c.OrderType,
Name = c.Name,
IsInactiveFlag = c.IsInactiveFlag
});