如何在c#实体框架Linq中编写左连接、分组和平均
简单来说,我需要在实体框架中编写以下SQL。我更喜欢在林克做。我正在使用mysql 到目前为止,我所做的如下如何在c#实体框架Linq中编写左连接、分组和平均,c#,entity-framework,linq,C#,Entity Framework,Linq,简单来说,我需要在实体框架中编写以下SQL。我更喜欢在林克做。我正在使用mysql 到目前为止,我所做的如下 var data = from p in _context.Product join o in _context.Order on p.Id equals o.ProductId into orderTemp from ord in orderTemp.DefaultIfEmpty() group p by p.Id in
var data = from p in _context.Product
join o in _context.Order on p.Id equals o.ProductId into orderTemp
from ord in orderTemp.DefaultIfEmpty()
group p by p.Id into gp
select new
{
p.Id,
p.Price,
p.CategoryId,
gp.Average(m => m.Rate)
};
我一整天都在努力做这件事。任何帮助都是非常宝贵的,我们将不胜感激。先谢谢你
上述操作不起作用,因为
m
引用的是产品的对象
您可以尝试从订单表中查找平均值,这里的问题是您需要选择左侧外部联接结果,然后对其进行分组
(from p in products
join o in Orders on p.id equals o.productId
into pg
from g in pg.DefaultIfEmpty()
select new { p.id, p.categoryId, p.price, g?.rate} into lg
group lg by lg.id into sg
from s in sg
select new { s.id, s.price, rate =sg.Average(r=> r.rate)}).Distinct().ToList();
谢谢所有试图帮助我的人。经过一番斗争,下面的东西对我起了作用
var data = from p in _context.Product
join o in _context.Order on p.Id equals o.ProductId into orderTemp
from ord in orderTemp.DefaultIfEmpty()
group ord by p into gp
select new
{
Id = gp.Key.Id,
Price = gp.Key.Price,
CategoryId = gp.Key.CategoryId,
Rate = gp.Average(m => m == null ? 0 : m.Rate)
};
groupbyp.Id进入gp
将产品分组在一起,您可以尝试groupbyp.Id进入gp
并查看m引用的对象。或者也可以将o.ProductId分组到gp
,因为p.Id
和o.ProductId
无论如何都是相等的。尝试使用将p.Id分组到gp选择新的{p.Id,p.Price,p.CategoryId,gp.Average(m=>m.ord.rate)}代码>。m
引用的对象是ord
,其中包含联接的Order
表。在选择group by子句中未列出的列时,不应执行sql查询。您是否尝试过在sql server中执行sql?在linq中,groupby
是否有效。它给出了这个错误,CS1525无效的表达式术语“by”
@JenishRabadiya是的,上面的SQL工作正常,并给出了预期的结果。我正在使用MySQL。我知道你的意思,但可能是因为,id是主键,它很有效。不管怎样,假设我将查询更改为具有多个group by,即使在这一点上,您能否帮助我获得上述的正确linq。谢谢@SAJ我找到了解决方案,但我也会尝试此解决方案。
var data = from p in _context.Product
join o in _context.Order on p.Id equals o.ProductId into orderTemp
from ord in orderTemp.DefaultIfEmpty()
group ord by p into gp
select new
{
Id = gp.Key.Id,
Price = gp.Key.Price,
CategoryId = gp.Key.CategoryId,
Rate = gp.Average(m => m == null ? 0 : m.Rate)
};