如何在实体框架 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));