繁体   English   中英

如何在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM