在Linq To Entities中使用多个列连接表 [英] Joining tables using more than one column in Linq To Entities

查看:147
本文介绍了在Linq To Entities中使用多个列连接表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Linq to Entities中的每一个联接示例仅涉及子句中的一列。如果我需要2个或更多列才能使加入工作,那么语法是什么?如果可能,我还需要一个Linq to Entities Query Expression和Method Based的例子。以下是我需要的例子。表1和表2之间没有关系。

Every single example of joins in Linq to Entities involves only one column in the on clause. What is the syntax if I need 2 or more columns to make the join work? I would need an example for Linq to Entities Query Expressions and Method Based also, if possible. Below is the example of what I need. There isn't a relationship between Table1 and 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


推荐答案

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

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}

使用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} 

这篇关于在Linq To Entities中使用多个列连接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆