这是根据条件将这些linq / lambda语句连接在一起的最佳方法吗?这样我就不必多次参加同一件事。
我不是专家,但似乎有些多余吗?也许执行路径不是最有效的! 例如。
var products = context.Products.Select(c => c);
if (input.DefendantId != null)
{
products =
from p in products
join pd in context.ProductDefendant
on p.Id equals pd.ProductId
where pd.DefendantId == input.DefendantId
select p;
}
if (input.DefendantCode != null && input.DefendantId == null)
{
products =
from p in products
join pd in context.ProductDefendant
on p.Id equals pd.ProductId
join d in context.Defendants
on pd.DefendantId equals d.Id
where d.DefendantCode.Any(rp => EF.Functions.Like(d.DefendantCode, "%" + input.DefendantCode + "%"))
select p;
}
if (input.ProductId != null)
{
products = products.Where(c => c.Id == input.ProductId);
}
if (input.ProductName != null && input.ProductId == null)
{
products = products.Where(c => EF.Functions.Like(c.ProductName, "%" + input.ProductName + "%"));
}
var productsVM =
from p in products
join pd in context.ProductDefendant
on p.Id equals pd.ProductId
join d in context.Defendants
on pd.DefendantId equals d.Id
select new GetProductsReturnViewModel
{
Id = p.Id,
ProductName = p.ProductName,
DefendantCode = d.DefendantCode
};
switch (input.SortBy + "_" + input.OrderBy)
{
case "productName_DESC":
productsVM = productsVM.OrderByDescending(c => c.ProductName);
break;
default:
productsVM = productsVM.OrderBy(c => c.ProductName);
break;
}
if (input.PageSize != 0)
{
productsVM = productsVM.Skip((input.Page - 1) * input.PageSize).Take(input.PageSize);
}
return productsVM;
答案 0 :(得分:0)
我将保留每个join
的第一次出现的结果,并将联接结果向下传递。
var ProdsProdDef = from p in context.Products
join pd in context.ProductDefendant on p.Id equals pd.ProductId
select new { p, pd };
if (input.DefendantId != null) {
ProdsProdDef = from ppd in ProdsProdDef
where ppd.pd.DefendantId == input.DefendantId
select ppd;
}
var ProdsProdDefDef = from ppd in ProdsProdDef
join d in context.Defendants on ppd.pd.DefendantId equals d.Id
select new { ppd.p, ppd.pd, d };
if (input.DefendantCode != null && input.DefendantId == null) {
ProdsProdDefDef = from ppdd in ProdsProdDefDef
where ppdd.d.DefendantCode.Any(rp => EF.Functions.Like(ppdd.d.DefendantCode, "%" + input.DefendantCode + "%"))
select ppdd;
}
if (input.ProductId != null) {
ProdsProdDefDef = ProdsProdDefDef.Where(ppdd => ppdd.p.Id == input.ProductId);
}
if (input.ProductName != null && input.ProductId == null) {
ProdsProdDefDef = ProdsProdDefDef.Where(ppdd => EF.Functions.Like(ppdd.p.ProductName, "%" + input.ProductName + "%"));
}
var productsVM = from ppdd in ProdsProdDefDef
select new GetProductsReturnViewModel {
Id = ppdd.p.Id,
ProductName = ppdd.p.ProductName,
DefendantCode = ppdd.d.DefendantCode
};