如何在C#实体框架Linq中编写左联接,分组和平均

编程入门 行业动态 更新时间:2024-10-21 15:57:25
本文介绍了如何在C#实体框架Linq中编写左联接,分组和平均的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

简单来说,我需要在实体框架中编写以下SQL.我宁愿在Lynq中这样做.我正在使用mysql

To put it in simple terms i need to write the following SQL in entity framework. I would prefer to do it in Lynq. I'm using mysql

SELECT `p`.`Id`, p.price, p.categoryid, avg(o.rate) FROM `Product` AS `p` LEFT JOIN `Order` AS `o` ON `p`.`Id` = `o`.`ProductId` group by p.id

我到目前为止所做的是下面的

What I have did so far is below

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) };

我整天都在努力做这件事.任何帮助将是非常有价值的,并受到赞赏.预先谢谢你.

I have been struggling o do this the whole day. Any help would be highly valuable and appreciated. Thank you in advance.

以上操作无效,因为 m 引用了 Product 的对象.

The above is not working, as m is referencing the object of Product.

推荐答案

感谢所有尝试帮助我的人.经过一番努力,下面的东西对我有用.

Thank you everyone who tried to help me out. After a struggle the below worked for me.

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) };

更多推荐

如何在C#实体框架Linq中编写左联接,分组和平均

本文发布于:2023-11-15 13:59:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1595067.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实体   框架   平均   如何在   Linq

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!