我正在尝试根据下面的SQL编写Linq to Entities Query
基本上我希望得到最后5个订单的清单,订单日期在(TitleDetails)的子详细信息表中
SELECT t.Name, t.LimpIsbn, t.CasedIsbn, max(td.OrderDate) LastOrder
FROM [inform].[dbo].[Titles] t
left join [inform].[dbo].[TitleDetails] td on t.id = td.TitleId
where td.OrderDate is not null
group by t.Name, t.LimpIsbn, t.CasedIsbn
order by max(td.OrderDate) desc
我的代码如下
var query = Context.Titles
.Include(x => x.MisAccount)
.Include(x => x.TitleDetails)
.Where(x => x.TitleDetails.Any());
if (!string.IsNullOrEmpty(model.MisCustomer))
{
query = query.Where(x => x.MisAccount.Code == model.MisCustomer);
}
if (!User.IsInRole(Permission.CanAccessAllCustomers.ToString()))
{
var predicate = PredicateBuilder.False<Title>();
foreach (var customer in validCustomers)
{
var cust = customer.Code;
predicate = predicate.Or(x => x.MisAccount.Code == cust);
}
query = query.AsExpandable().Where(predicate);
}
model.LatestOrders = query.Take(5)
在视图中可以枚举LatestOrders。
我已经查看了有关Linq Group的各种其他来源,这些来源与单表分组有关,我正努力将其转换为多表。
答案 0 :(得分:1)
几乎就是那样
var last5Item = from td in Context.TitleDetails.OrderByDescending(i => i.OrderDate).Take(5)
join t in Context.Titles on td.TitleId equals t.id
select ..
答案 1 :(得分:1)
您的SQL查询可以转换为此linq查询:
var query =(from t in Context.Titles
join td in Context.TitleDetails on t.id equals td.TitleId into tds
from e in tds.DefaultIfEmpty()
where e.OrderDate!=null
group e.OrderDate by new {t.Name, t.LimpIsbn, t.CasedIsbn} into groups
from g in groups
select new { Name = m.Key.Name,
LimpIsbn = g.Key.LimpIsbn,
CasedIsbn = g.Key.CasedIsbm,
LastOrder = g.Max(x => x)})
.OrderBy(e=>e.LastOrder).Take(5);