Bre*_*ogt 121 entity-framework entity-framework-4 entity-framework-4.1 entity-framework-5
我正在使用Entity Framework 5 code first
和ASP.NET MVC 3
.
我正在努力让一个子对象的子对象填充.以下是我的课程..
申请类;
public class Application
{
// Partial list of properties
public virtual ICollection<Child> Children { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
儿童班:
public class Child
{
// Partial list of properties
public int ChildRelationshipTypeId { get; set; }
public virtual ChildRelationshipType ChildRelationshipType { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
ChildRelationshipType类:
public class ChildRelationshipType
{
public int Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
存储库中GetAll方法的一部分,用于返回所有应用程序:
return DatabaseContext.Applications
.Include("Children");
Run Code Online (Sandbox Code Playgroud)
Child类包含对ChildRelationshipType类的引用.要与应用程序的孩子一起工作,我会有这样的事情:
foreach (Child child in application.Children)
{
string childName = child.ChildRelationshipType.Name;
}
Run Code Online (Sandbox Code Playgroud)
我在这里得到一个错误,即对象上下文已经关闭.
如何指定每个子对象必须包含ChildRelationshipType
像我上面所做的那样的对象?
Rya*_*ies 239
如果包含库System.Data.Entity
,则可以使用Include()
方法的重载,该方法采用lambda表达式而不是字符串.然后Select()
,您可以使用Linq表达式而不是string
路径来覆盖孩子.
return DatabaseContext.Applications
.Include(a => a.Children.Select(c => c.ChildRelationshipType));
Run Code Online (Sandbox Code Playgroud)
Hay*_*yha 65
使用.NET Core中的EF Core,您可以使用以下关键字ThenInclude
:
return DatabaseContext.Applications
.Include(a => a.Children).ThenInclude(c => c.ChildRelationshipType);
Run Code Online (Sandbox Code Playgroud)
包括儿童收藏中的儿童:
return DatabaseContext.Applications
.Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType1)
.Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType2);
Run Code Online (Sandbox Code Playgroud)
Bre*_*ogt 22
我最终做了以下工作:
return DatabaseContext.Applications
.Include("Children.ChildRelationshipType");
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
93085 次 |
最近记录: |