【问题标题】:Entity Framework nesting variables实体框架嵌套变量
【发布时间】:2018-01-27 01:58:35
【问题描述】:

我在实体中有以下设置:

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

多个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_htc 嵌套列表的 t_ht 或 单个 t_ct_htc 的嵌套列表

但是,我想要实现的是:

单个t_ht,带有t_htc的嵌套列表,然后t_htct_c中包含相应的条目

我知道我可以通过执行将queryC 连接到queryHt 的连接来实现这一点,但这似乎还有很长的路要走。

实体确实可以实现我想要做的事情吗?

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

【问题讨论】:

    标签: c# entity-framework linq include entity


    【解决方案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;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多