Joining tables using more than one column in Linq To Entities
For method based query:
var query = ctx.Table1s.Join(ctx.Table2s,
a => new { a.ID1Table1, a.ID2Table1 },
b => new { b.ID1Table2, b.ID2Table2 },
(t1, t2) => new {
t1.ID1Table1, t1.ID2Table1, t1.Value1Table1, t2.ID3Table2, t2.Value1Table2
});
if happen to be key column name is different between two tables, then should assign a same propery name in outer and inner selector. eg:
var query = ctx.Table1s.Join(ctx.Table2s,
a => new { key1 = a.ID1Table1, key2 = a.ID2Table1 },
b => new { key1 = b.ID1Table2, key2 = b.ID2Table2 },
(t1, t2) => new {
t1.ID1Table1, t1.ID2Table1, t1.Value1Table1, t2.ID3Table2, t2.Value1Table2
});
to verify the above query, print the sql statement:
string sql = ((System.Data.Objects.ObjectQuery)query).ToTraceString();
You can write it using two from expressions like below:
from a in Table1s
from b in Table2s
where a.ID1Table1 == b.ID1Table2 && a.ID2Table1 == b.ID2Table2
select new {a.ID1Table1, a.ID2Table1, a.Value1Table1, b.ID3Table2, b.Value1Table2}
Using join:
from a in Table1s
join b in Table2s on new{PropertyName1 = a.ID1Table1, PropertyName2 = a.ID2Table1} equals new{PropertyName1 = b.ID1Table2, PropertyName2 = b.ID2Table2}
select new {a.ID1Table1, a.ID2Table1, a.Value1Table1, b.ID3Table2, b.Value1Table2}