[英]How to group by property of child entity and get sum of child entity in linq?
[英]How to select Distinct / Group By child property in both LINQ method and syntax?
我有课
public class Parent
{
[Key]
public int ParentID { get; set;}
public virtual ICollection<Child> Childs { get; set; }
}
public class Child
{
[Key]
public int ChildID { get; set; }
public int Grade { get; set; }
public int ParentID { get; set; }
[ForeignKey("ParentID")]
public virtual Parent Parent { get; set; }
}
我需要的东西
SELECT
Child.Grade
FROM
Parent
INNER JOIN Child ON
Parent.ParentID = Child.ParentID
WHERE
Parent.ParentID = 1
GROUP BY
Child.Grade
和
SELECT DISTINCT
Child.Grade
FROM
Parent
INNER JOIN Child ON
Parent.ParentID = Child.ParentID
WHERE
Parent.ParentID = 1
任何帮助将不胜感激。 谢谢
没有理由加入父母,因为您可以只使用Child.ParentId
无论如何,您可以执行以下操作:
var result = db.Set<Child>().Where(c => c.Parent.ParentId = 1).GroupBy(c => c.Grade);
还是没有加入;
var result = db.Set<Child>().Where(c => c.ParentId = 1).GroupBy(c => c.Grade);
唯一的区别是:
var result = db.Set<Child>().Where(c => c.ParentId = 1).Select(c => c.Grade).Distinct();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.