linq 如何在Entity Framework Core中将2个父级包含到一个子级列表中?[duplicate]

k97glaaz  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(146)

此问题在此处已有答案

EFCore Linq ThenInclude Two Foreign Keys To Same Table(1个答案)
15天前关闭。
我有这个类和一个上下文类:

public class Parent
{
    public int Id { get; set; }
    public virtual ICollection<Child> Children { get; set; }
}

public class Child
{
    public int Id { get; set; }

    public int ParentId { get; set; }
    public int ForeignId { get; set; }

    [ForeignKey("ParentId")]
    public virtual Parent Parent{ get; set; }
    [ForeignKey("ForeignId")]
    public virtual Foreign Foreign{ get; set; }

    public virtual ICollection<GrandChild> GrandChildren { get; set; }
}

public class GrandChild
{
    public int Id { get; set; }
    public int ChildId { get; set; }

    [ForeignKey("ChildId")]
    public virtual Child Child{ get; set; }
}

public class Foreign
{
    public int Id { get; set; }
    public string name { get; set; }

    public virtual ICollection<Child> Children { get; set; }
}

我想显示一个父表列表,其中包括他们的孩子和孙子。我也想包括Foreign表,因为我需要它的字段。我写了下面的代码:

var list = context.Parents.Include(p => p.Children).ThenInclude(p => p.GrandChildren).Tolist();

如何在此查询中添加或包含外表?

我写了下面的代码,但它有错误:

var list = context.Parents
    .Include(p => p.Children)
        .ThenInclude(p => p.GrandChildren)
    .Include(p => p.Children.FirstOrDefault().Foreign).Tolist();
9vw9lbht

9vw9lbht1#

需要添加的2项包括:

var list = context.Parents

                .Include(p => p.Children)
                .ThenInclude(c => c.GrandChildren)
                .Include(p => p.Children)
                .ThenInclude(c => c.Foreign).ToList();

相关问题