0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【C#】LINQでJOINは、メソッド構文よりクエリ構文

Last updated at Posted at 2020-05-26

LINQで複数テーブルをJoinする場合は、メソッド構文ではなくクエリ構文で記述した方が可読性は高い

複数エンティティをメソッド構文で内部結合すると可読性が低い。
複数エンティティ結合する必要がある場合は、クエリ構文で記述した方が可読性は上がる。

メソッド構文とクエリ構文で比較

4テーブル結合した場合のメソッド構文クエリ構文の例

メソッド構文の例

            var query =
                db.Parent
                .Join(db.ChildA, x => x.id, y => y.id, (p, a) => new { p, a })
                .Join(db.ChildB, x => x.p.id, y => y.id, (grp, b) => new { grp, b })
                .Join(db.ChildC, x => x.grp.p.id, y => y.id, (grp, c) => new { grp, c })
                .Join(db.ChildD, x => x.grp.grp.p.id, y => y.id, (grp, d) => new { grp, d })
                .Select(x => new { x.grp.grp.grp.p, x.grp.grp.grp.a, x.grp.grp.b, x.grp.c, x.d });

クエリ構文の例

            var query =
                from p in db.Parent
                join a in db.ChildA on p.id equals a.id
                join b in db.ChildB on p.id equals b.id
                join c in db.ChildC on p.id equals c.id
                join d in db.ChildD on p.id equals d.id
                select new {p,a,b,c,d};
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?