LoginSignup
3
3

More than 5 years have passed since last update.

Linq to Entityで複合キー内部結合(inner join on malutiple column for linq to entity)

Last updated at Posted at 2015-08-07

このようなSQL

複合.sql
SELECT a.* FROM tableA inner join tableB 
on 
tableA.Id = tableB.Id
and
tableA.Code = tableB.Code
chain_code_join.cs
var test = context.tableA
.Join(context.tableB,
    (a) => new {a.Id,a.Code},
    (b) => new {b.Id,b.Code},
    (a,b) => a
);

↓chain codeじゃない版(動かしていない自信なし(大体こんな感じ))

chain_code否_join.cs
var test = from a in context.tableA
    join b in context.tableB 
    on
      (a) => new {a.Id,a.Code}
    equals
      (b) => new {b.Id,b.Code}
    select a;

ちなみに名前が違うcolumn同士を結合しようとすると意味不明のエラーが出る。
↓エラーになります。

error.cs
SELECT a.* FROM tableA inner join tableB 
on 
tableA.Id = tableB.tableAId
and
tableA.Code = tableB.tableACode

こんな時はエイリアスを用意してやらないといけない。
↓エイリアスで指定するとうまくいく例

filename
var test = context.tableA
.Join(context.tableB,
    (a) => new {Id = a.Id,Code = a.Code},
    (b) => new {Id = b.Id,Code = b.Code},
    (a,b) => a
);

スター型の例

filename
var test = context.tableA
.Join(context.tableB,
    (a) => new {Id = a.Id,Code = a.BCode},
    (b) => new {Id = b.Id,Code = b.Code},
    (a,b) => new { a, b})
.Join(context.tableB,
    (ab) => new {Id = ab.Id,Code = ab.CCode},
    (c) => new {Id = c.Id,Code = c.Code},
    (ab,b) => new { ab, b})
);

という感じになります。

ビバ!りんくとうえんてぃてぃ!

MSDNのAPIライブラリはすごい網羅しているのに別言語に変更したくなるくらい読みにくいのである。
https://msdn.microsoft.com/ja-jp/library/Bb311040(v=VS.120).aspx

3
3
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
3
3