简体   繁体   English

实体框架-包含多个级别的属性

[英]Entity Framework - Include multiple level properties

I am trying to get a table from database using entity framework. 我正在尝试使用实体框架从数据库中获取表。

The table has reference to other table which again has reference to other tables. 该表引用了其他表,该表又引用了其他表。 I know how to include other tables. 我知道如何包括其他表格。 And according to this answer and this MSDN page including multiple levels are like this: 根据这个答案,这个包含多个级别的MSDN页面是这样的:

entity.TableLevel1.Include(tLvl1=>tLvl1.TableLevel2.Select(tLvl2=>tLvl2.TableLevel3));

But my question is, how to include another table at level 3 ? 但是我的问题是,如何在3级包含另一个表?

This seems not to work: 这似乎不起作用:

entity.TableLevel1
          .Include(tLvl1=>tLvl1.TableLevel2
               .Select(tLvl2=>tLvl2.TableLevel3)
               .Select(tLvl2 => tLvl2.AnotherTableLevel3);

Add another Include call: 添加另一个Include调用:

entity.TableLevel1.Include(tLvl1=>tLvl1.TableLevel2.Select(tLvl2=>tLvl2.TableLevel3))
                  .Include(tLvl1=>tLvl1.TableLevel2.Select(tLvl2=>tLvl2.AnotherTableLevel3));

If you want to load related entities that are at the same level you should call Include extension method for each of them. 如果要加载相同级别的相关实体,则应为每个实体调用Include扩展方法。

You can make multiple Include() calls: 您可以进行多个Include()调用:

entity.TableLevel1.Include(t1 => t1.TableLevel2);
entity.TableLevel1.Include(t1 => t1.TableLevel2.Select(t2 => t2.TableLevel3));
entity.TableLevel1.Include(t1 => t1.TableLevel2.Select(t2 => t2.AnotherTableLevel3));

or 要么

entity.TableLevel1.Include("TableLevel2");
entity.TableLevel1.Include("TableLevel2.TableLevel3");
entity.TableLevel1.Include("TableLevel2.AnotherTableLevel3");

But you can mark your navigation properties as virtual and will be lazy loading, so you dont need to make the Include() calls: 但是您可以将导航属性标记为virtual并且将延迟加载,因此您无需进行Include()调用:

class TableLevel1
{
    public virtual TableLevel2 TableLevel2 { get; set; }
}

class TableLevel2
{
    public virtual TableLevel3 TableLevel3 { get; set; }

    public virtual TableLevel3 AnotherTableLevel3 { get; set; }
}

Using EF 6.2 (not core) this gave me a headache for a few hours, only to find that the reason this wasn't working... 使用EF 6.2(不是核心)这让我头疼了几个小时,却发现这不起作用的原因...

.Include("InspectionResultsByPerspective") .Include("InspectionResultsByPerspective.InspectionResults") .Include("InspectionResultsByPerspective.InspectionResults.PreparationTasksResults") .Include(“ InspectionResultsByPerspective”).Include(“ InspectionResultsByPerspective.InspectionResults”).Include(“ InspectionResultsByPerspective.InspectionResults.PreparationTasksResults”)

was because the type PreparationTasksResults had no default ctor!!! 是因为类型PreparationTasksResults没有默认的ctor !!! ahhh! 啊!

Give it a default ctor and you can include to your heart's content :) or so it seems for me 给它一个默认的ctor,您就可以加入您的内心内容了:)或对我来说似乎如此

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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