SQL查询到LINQ到实体框架
我想知道是否甚至可以将下面的SQL查询写为LINQ to Entity语句。以下是我试图找出的一个真实世界问题的简化示例:SQL查询到LINQ到实体框架
Select
c.CustomerID,
c.CustomerName,
(Select count(p.ProductID) from Products p
where p.CustomerID = c.CustomerID and p.Category = 'HomeAppliance') as ApplianceCount,
(Select count(p.ProductID) from Products p
where p.CustomerID = c.CustomerID and p.Category = 'Furnishing') as FurnishingCount
from Customer c
where
c.CustomerMarket = 'GB'
order by c.CustomerID desc;
任何建议,将不胜感激。需要考虑LINQ to Entity的性能,因为它涉及到检索很多行。
喜欢的东西(假设明显的情况下):在LINQ到实体
var res = await (from c in dbCtx.Customers
where c.CustomerMarket = "GB"
let homeCount = c.Products.Where(p => p.Category = "HomeAppliance").Count()
let furnCount = c.Products.Where(p => p.Category = "Furnishing").Count()
orderby c.CustomerID descending
select new {
CustomerID = c.CustomerID,
CustomerName = c.CustomerName,
ApplianceCount = homeCount,
FurnishingCount = furnCount
}).ToListAsync();
性能将需要考虑,因为这将涉及大量的检索行。
之后,您需要确认生成的SQL是否合理(帮助获取的列数不是您需要的最佳方法),然后再考虑服务器运行该SQL的性能。
谢谢理查德。正是我在找什么。我需要像'让'那样的东西。 – NullReference
是的,这是可能的:
customers
.Where(cust => cust.CustomerMarket == "GB")
.Select(cust => new
{
cust.CustomerId,
cust.CustomerName,
ApplianceCount = products
.Where(prod => prod.CustomerId == cust.CustomerId && prod.Category == "HomeAppliance")
.Select(prod => prod.ProductId)
.Count(),
FurnishingCount = products
.Where(prod => prod.CustomerId == cust.CustomerId && prod.Category == "Furnishing")
.Select(prod => prod.ProductId)
.Count(),
});
这里既有customers
和products
是IQueryable<T>
S中的相应的类型的。
谢谢。但我认为使用'让'可以更好地简化查询。 – NullReference
我非常确定它们的工作方式是一样的,所以一般情况下您更喜欢方法语法和查询语法。对我来说,在同一个地方混合使用这种方法很简单,我的个人偏好是方法语法,这就是为什么我这样写的原因,但当然,这可能不适用于你:) –
请不要只发布SQL并要求转换。至少显示一个类模型,以便导航属性和关联的多样性是可见的。此外,展示你自己的第一个努力。他们向我们澄清的比你想象的更多。 –