Entity Framework - 複数レベルのプロパティを含める 質問する

Entity Framework - 複数レベルのプロパティを含める 質問する

Include() メソッドは、オブジェクトのリストに対して非常にうまく機能します。しかし、2 レベル深くする必要がある場合はどうでしょうか。たとえば、以下のメソッドは、ここに示されているプロパティを含む ApplicationServers を返します。ただし、ApplicationsWithOverrideGroup は、他の複雑なオブジェクトを保持する別のコンテナーです。そのプロパティに対しても Include() を実行できますか。または、そのプロパティを完全に読み込むにはどうすればよいですか。

現状では、この方法は、

public IEnumerable<ApplicationServer> GetAll()
{
    return this.Database.ApplicationServers
        .Include(x => x.ApplicationsWithOverrideGroup)                
        .Include(x => x.ApplicationWithGroupToForceInstallList)
        .Include(x => x.CustomVariableGroups)                
        .ToList();
}

Enabled プロパティ (下記) のみが設定され、Application または CustomVariableGroup プロパティ (下記) は設定されません。 これを実現するにはどうすればよいでしょうか?

public class ApplicationWithOverrideVariableGroup : EntityBase
{
    public bool Enabled { get; set; }
    public Application Application { get; set; }
    public CustomVariableGroup CustomVariableGroup { get; set; }
}

ベストアンサー1

EF6の場合

using System.Data.Entity;

query.Include(x => x.Collection.Select(y => y.Property))

ラムダを受け入れるusing System.Data.Entity;のバージョンを取得するには、必ず を追加してください。Include


EFコアの場合

新しい方法を使用するThenInclude

using Microsoft.EntityFrameworkCore;

query.Include(x => x.Collection)
     .ThenInclude(x => x.Property);

おすすめ記事