我需要用一个查询来编写它。 根据参数,如果参数大于零,则必须保留其中一个条件。如果参数中没有涉及此参数,则必须包含此参数。
var myRegionId = 0;
if (!string.IsNullOrEmpty(regionId))
{
myRegionId = int.Parse(regionId);
}
IOrderedQueryable price;
if (myRegionId>0)
{
price = (from p in _db.PRICEs
join good in _db.GOODs on p.good_id equals good.id
join gname in _db.spr_goods_names on good.goods_name_id equals gname.id
where ******p.region_id == myRegionId &&** gname.name.ToLower().Contains(filterText.ToLower())****
group p by new{ p.good_id} into g
select new
{
GoodId = g.Key.good_id,
Promotion = g.Count(x => x.promotion != ""),
MinPrice = g.Min(x => x.good_price),
DistributorCount = g.Count(x => x.distributor_id != null)
}
).OrderByDescending(x => x.DistributorCount).Take(100).OrderBy(x => x.MinPrice);
}else
{
price = (from p in _db.PRICEs
join good in _db.GOODs on p.good_id equals good.id
join gname in _db.spr_goods_names on good.goods_name_id equals gname.id
**where gname.name.ToLower().Contains(filterText.ToLower())**
group p by new { p.good_id } into g
select new
{
GoodId = g.Key.good_id,
Promotion = g.Count(x => x.promotion != ""),
MinPrice = g.Min(x => x.good_price),
DistributorCount = g.Count(x => x.distributor_id != null)
}
).OrderByDescending(x => x.DistributorCount).Take(100).OrderBy(x => x.MinPrice);
}
答案 0 :(得分:1)
这个怎么样?
price = (from p in _db.PRICEs
join good in _db.GOODs on p.good_id equals good.id
join gname in _db.spr_goods_names on good.goods_name_id equals gname.id
where (myRegionId <= 0 || p.region_id == myRegionId) && gname.name.ToLower().Contains(filterText.ToLower())
group p by new{ p.good_id} into g
select new
{
GoodId = g.Key.good_id,
Promotion = g.Count(x => x.promotion != ""),
MinPrice = g.Min(x => x.good_price),
DistributorCount = g.Count(x => x.distributor_id != null)
}).OrderByDescending(x => x.DistributorCount).Take(100).OrderBy(x => x.MinPrice);
如果myRegionId <= 0
,则评估为true
,p.region_id == myRegionId
未评估,因此会被忽略。
答案 1 :(得分:1)
使用延迟加载功能,只要您不需要数据,就可以操纵查询构建。
var a = from p in _db.PRICEs
...
if (condition) a = a.where...
else a=a.where...
if (condition2) a = a.where...
var b = from a ....
一旦你迭代foreach或者调用ToList数据就会被下载,并且查询会提交给db。所以在发布之前你可以做你需要的。
PS:使用分析器检查发送给BD的查询以优化性能。有时ORM可以构造非常巨大的东西,并且会损害性能。
答案 2 :(得分:1)
你也可以将它分成几部分,如下所示:
var query = from p in _db.PRICEs
join good in _db.GOODs on p.good_id equals good.id
join gname in _db.spr_goods_names on good.goods_name_id equals gname.id
where gname.name.ToLower().Contains(filterText.ToLower())
select p;
if (myRegionId>0)
{
query = query.Where(p => p.region_id == myRegionId);
}
var price = from p in query
group p by new{ p.good_id} into g
select new
{
GoodId = g.Key.good_id,
Promotion = g.Count(x => x.promotion != ""),
MinPrice = g.Min(x => x.good_price),
DistributorCount = g.Count(x => x.distributor_id != null)
}).OrderByDescending(x => x.DistributorCount).Take(100).OrderBy(x => x.MinPrice);