如何在实体框架 5 中包含子对象的子对象 [英] How to include a child object's child object in Entity Framework 5

查看:31
本文介绍了如何在实体框架 5 中包含子对象的子对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先使用 Entity Framework 5 代码ASP.NET MVC 3.

我正在努力让子对象的子对象填充.下面是我的课..

I am struggling to get a child object's child object to populate. Below are my classes..

应用类;

public class Application
{
     // Partial list of properties

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

子类:

public class Child
{
     // Partial list of properties

     public int ChildRelationshipTypeId { get; set; }

     public virtual ChildRelationshipType ChildRelationshipType { get; set; }
}

ChildRelationshipType 类:

ChildRelationshipType class:

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

     public string Name { get; set; }
}

存储库中 GetAll 方法的一部分,用于返回所有应用程序:

Part of GetAll method in the repository to return all the applications:

return DatabaseContext.Applications
     .Include("Children");

Child 类包含对 ChildRelationshipType 类的引用.要与应用程序的孩子一起工作,我会有这样的事情:

The Child class contains a reference to the ChildRelationshipType class. To work with an application's children I would have something like this:

foreach (Child child in application.Children)
{
     string childName = child.ChildRelationshipType.Name;
}

我在这里收到一个错误,指出对象上下文已经关闭.

I get an error here that the object context is already closed.

如何指定每个子对象必须像我上面所做的那样包含 ChildRelationshipType 对象?

How do I specify that each child object must include the ChildRelationshipType object like what I did above?

推荐答案

如果您包含库 System.Data.Entity,您可以使用 Include() 的重载> 采用 lambda 表达式而不是字符串的方法.然后,您可以使用 Linq 表达式而不是 string 路径对子项进行 Select().

If you include the library System.Data.Entity you can use an overload of the Include() method which takes a lambda expression instead of a string. You can then Select() over children with Linq expressions rather than string paths.

return DatabaseContext.Applications
     .Include(a => a.Children.Select(c => c.ChildRelationshipType));

这篇关于如何在实体框架 5 中包含子对象的子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆