EF代码优先:如何加载相关数据(父子孙)?
我有这个实体:
public class DynamicPage {
public int PageId { get; set; }
public int Order { get; set; }
public string MenuText { get; set; }
public string MenuHover { get; set; }
public int? ParentId { get; set; }
public virtual DynamicPage Parent { get; set; }
public virtual ICollection<DynamicPage> Children { get; set; }
}
这个实体可能有 3 个级别:父级 ->儿童->孙子。如何加载所有关联子项(级别 2)的父项(级别 1)以及每个子项、关联孙子项(级别 3)(如果有)?谢谢帮忙。
I have this entity:
public class DynamicPage {
public int PageId { get; set; }
public int Order { get; set; }
public string MenuText { get; set; }
public string MenuHover { get; set; }
public int? ParentId { get; set; }
public virtual DynamicPage Parent { get; set; }
public virtual ICollection<DynamicPage> Children { get; set; }
}
This entity may have 3 level: Parent -> Child -> Grandchild. How can I load the Parent (level 1) whit all associated children (level 2) and for each child, associated grandchild (level 3) if any? Thanks to help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
EF 4.1 功能和语法:
EF 4.1 feature and syntax:
如果您想让自己的生活变得轻松,请遵循 EF Code First 约定,将表 ID 命名为
Id
(或者,表名称 +Id
,例如,DyanmicPageId
)。这应该给您留下类似这样的结果:
然后您需要在
DbContext
类的OnModelCreating
方法中显式设置父级和子级之间的关系。然后,您可以根据需要选择子代或孙代:
If you want to make life easy on yourself, follow the EF Code First conventions of naming your table IDs simply
Id
(or, alternatively, name of table +Id
, e.g.,DyanmicPageId
).This should leave you with something like this:
Then you need to set up the relationship between parents and children explicitly in an
OnModelCreating
method in yourDbContext
class.You can then select children or grandchildren as needed: