167

と を使用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ですか?

4

4 に答える 4

282

ライブラリを含めると、文字列の代わりにラムダ式を受け取るメソッドSystem.Data.Entityのオーバーロードを使用できます。次に、パスではなくLinq式を使用して子をオーバーInclude()できます。Select()string

return DatabaseContext.Applications
     .Include(a => a.Children.Select(c => c.ChildRelationshipType));
于 2012-10-24T11:39:11.937 に答える
23

私は次のことをすることになりました、そしてそれは働きます:

return DatabaseContext.Applications
     .Include("Children.ChildRelationshipType");
于 2012-10-24T12:42:45.280 に答える
1

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();
}
于 2016-04-08T17:52:19.920 に答える