实体框架嵌套变量

时间:2017-08-18 11:33:39

标签: c# entity-framework linq include entity

我在实体中有以下设置:

public class t_HT
{
    public int UNID { get; set; }

    public string Name { get; set; }

    public ICollection<t_HTC> Comments { get; set; }

}

public class t_HTC
{
    public int UNID { get; set; }

    public int HTID { get; set; }

    [ForeignKey("HTID")]
    public t_HT HT { get; set; }

    public int CId { get; set; }

    [ForeignKey("CId")]
    public t_C C { get; set; }
}

public class t_C
{
    public int UNID { get; set; }

    public string Name { get; set; }

    public ICollection<t_HTC> Comments { get; set; }
}

关系如下:

许多t_HTC到一个t_HT

一个t_HT到多个t_HTC

AND

许多t_HTC到一个t_C

一个t_C到多个t_HTC

此设置可以正常工作并实现我的需要。

但是,使用C#Linq/Entity查询时,我可以执行以下操作:

var queryHt = context.ht.include(x => x.htc);

var queryC = context.c.include(x => x.htc);

其中任何一个都会返回一个t_ht,其中包含t_htc OR的嵌套列表 单个t_c,其嵌套列表为t_htc

但是,我想要实现的目标是:

单个t_ht,其中包含t_htc的嵌套列表,然后t_htc包含t_c中的相应条目

我知道我可以通过执行将queryC加入queryHt的联接来实现此目的,但这似乎还有很长的路要走。

当然,实体可以实现我想做的事情吗?

请注意变量名称已针对此问题进行了调整,在我的实际代码中不是这样。

1 个答案:

答案 0 :(得分:1)

你可以用这个来实现你想要的目标:

var queryHt = context.ht.Include("htc.C");

或使用strong typed version

var queryHt = context.ht.Include(x => x.htc.Select(y => y.C));

强类型版本需要添加using System.Data.Entity;

相关问题