LoginSignup
1
1

More than 5 years have passed since last update.

EntityFrameworkのInclude拡張ライブラリ

Last updated at Posted at 2016-03-05

EntityFrameworkで関連エンティティをロードするInclude()を拡張するライブラリを作りました。
EntityFramework.Include

NuGetからインストールできます。
https://www.nuget.org/packages/EntityFramework.Include

PM> Install-Package EntityFramework.Include

READMEを見れば使い方はわかると思いますが、Includeで関連エンティティのコレクションを読み込むとき、フィルターで条件を指定して読み込む機能を実装しています。

内部で何をしているか

以下のようなエンティティがあったとき

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

    public int Age { get; set; }

    [NotMapped]
    public int ChildrenCount { get; set; }

    public List<Child> Children { get; set; } = new List<Child>();
}

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

    public int Age { get; set; }
}

このような操作では

context.ParentSet.Include(p => p.Children, p => p.Children.Take(10).ToList())
                 .Include(p => P.ChildrenCount, p => p.Children.Count)
                 .ToListWithInclude();

TypeBuilderParentを継承したclassを作り
式木をこねて

Select(p => new Parent_継承()
                {
                    Id = p.Id,
                    Age = p.Age,
                    Children = p.Children.Take(10).ToList(),
                    ChildrenCount = p.Children.Count
                })

相当のExpressionを組み立ててToList()
最後にParentにキャストしてListを返しています。
返ってきたエンティティたちはDetached状態なので注意が必要です。

バグレポートだったりほしい機能を作者Twitterに投げてくれるとうれしいのでよろしくお願いします。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1