그리고를 사용 Entity Framework 5 code first
하고 ASP.NET MVC 3
있습니다.
자식 개체의 자식 개체를 채우는 데 어려움을 겪고 있습니다. 아래는 내 수업입니다.
응용 수업;
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()
. 그런 다음 경로가 Select()
아닌 Linq 표현을 가진 어린이를 처리 할 수 있습니다 string
.
return DatabaseContext.Applications
.Include(a => a.Children.Select(c => c.ChildRelationshipType));
답변
.NET Core의 EF Core를 사용하면 다음 키워드를 사용할 수 있습니다 ThenInclude
.
return DatabaseContext.Applications
.Include(a => a.Children).ThenInclude(c => c.ChildRelationshipType);
어린이 컬렉션의 어린이 포함 :
return DatabaseContext.Applications
.Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType1)
.Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType2);
답변
나는 다음을하고 결국 작동합니다 :
return DatabaseContext.Applications
.Include("Children.ChildRelationshipType");
답변
Generic Repository 패턴을 사용하고이를위한 일반 솔루션을 구현하는 좋은 예는 다음과 같습니다.
public IList<TEntity> Get<TParamater>(IList<Expression<Func<TEntity, TParamater>>> includeProperties)
{
foreach (var include in includeProperties)
{
query = query.Include(include);
}
return query.ToList();
}