gpt4 book ai didi

entity-framework - 如何在 Entity Framework 5 中包含子对象的子对象

转载 作者:行者123 更新时间:2023-12-03 04:33:31 26 4
gpt4 key购买 nike

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

我正在努力填充子对象的子对象。以下是我的类(class)..

应用程序类;

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 类:

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

public string Name { get; set; }
}

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

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

Child 类包含对 ChildRelationshipType 类的引用。要与应用程序的子级一起工作,我需要这样的东西:

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

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

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

最佳答案

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

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

关于entity-framework - 如何在 Entity Framework 5 中包含子对象的子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13047845/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com