使用Linq To Entities中的多个列连接表

Pas*_*cal 22 linq-to-entities entity-framework entity-framework-4

Linq to Entities中的每个连接示例都只涉及on子句中的一列.如果我需要2个或更多列来完成join工作,那么语法是什么?如果可能的话,我还需要一个Linq to Entities查询表达式和基于方法的示例.以下是我需要的例子.Table1和Table2之间没有关系.

CREATE TABLE dbo.Table1 (
  ID1Table1 INT NOT NULL,
  ID2Table1 SMALLDATETIME NOT NULL,
  Value1Table1 VARCHAR(50) NOT NULL,
  CONSTRAINT PK_Table1 PRIMARY KEY (ID1Table1, ID2Table1));
CREATE TABLE dbo.Table2 (
  ID1Table2 INT NOT NULL,
  ID2Table2 SMALLDATETIME NOT NULL,
  ID3Table2 INT NOT NULL,
  Value1Table2 VARCHAR(50) NOT NULL,
  CONSTRAINT PK_Table2 PRIMARY KEY (ID1Table2, ID2Table2, ID3Table2));

SELECT a.ID1Table1, a.ID2Table1, a.Value1Table1, b.ID3Table2, b.Value1Table2
FROM dbo.Table1 a JOIN dbo.Table2 b
  ON a.ID1Table1 = b.ID1Table2
  AND a.ID2Table1 = b.ID2Table2
Run Code Online (Sandbox Code Playgroud)

Cha*_*ndu 33

您可以使用以下表达式中的两个来编写它:

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}
Run Code Online (Sandbox Code Playgroud)

使用join:

from a in Table1s  
join b in Table2s on new{a.ID1Table1, a.ID2Table1} equals new{b.ID1Table2,b.ID2Table2}
select new {a.ID1Table1, a.ID2Table1, a.Value1Table1, b.ID3Table2, b.Value1Table2} 
Run Code Online (Sandbox Code Playgroud)


Len*_*eng 19

对于基于方法的查询:

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
});
Run Code Online (Sandbox Code Playgroud)

如果恰好两个表之间的键列名称不同,那么应该在外部和内部选择器中分配相同的属性名称.例如:

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
});
Run Code Online (Sandbox Code Playgroud)

要验证上面的查询,请打印sql语句:

string sql = ((System.Data.Objects.ObjectQuery)query).ToTraceString();
Run Code Online (Sandbox Code Playgroud)