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

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

问题描述

我正在使用实体框架5代码首先 ASP.NET MVC 3



我正在努力获取一个子对象的子对象来填充。以下是我的课程。



应用程序类;

  public class应用程序
{
//部分属性列表

public virtual ICollection< Child>孩子{get;组;
}

小孩类:

  public class Child 
{
//部分属性列表

public int ChildRelationshipTypeId {get;组; }

public virtual ChildRelationshipType ChildRelationshipType {get;组; }
}

ChildRelationshipType类:

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

public string Name {get;组; }
}

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

  return DatabaseContext.Applications 
.Include(Children);

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

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

我在这里收到一个错误,表明对象上下文已经关闭。 >

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

解决方案

如果您包含库 System.Data.Entity ,可以使用 Include()方法,它采用lambda表达式而不是字符串。然后,您可以使用Linq表达式而不是 string 路径的小孩选择()。

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


I am using Entity Framework 5 code first and ASP.NET MVC 3.

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

Application class;

public class Application
{
     // Partial list of properties

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

Child class:

public class Child
{
     // Partial list of properties

     public int ChildRelationshipTypeId { get; set; }

     public virtual ChildRelationshipType ChildRelationshipType { get; set; }
}

ChildRelationshipType class:

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

     public string Name { get; set; }
}

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

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

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.

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

解决方案

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));

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

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