Linq to Sql join with select

时间:2011-08-24 09:28:55

标签: sql linq

我正在尝试创建Linq,它执行与下面的SQL相同的连接:

select *
    from Table1
        inner join Table2 on Table1.ID = (select ID from Table2 where ID= 281026)

(我知道这样做是没有意义的,但我只是想知道加入背后的原则是否可行)

我到目前为止Linq:

from t1 in ctxt.Table1
     join t2 in ctxt.Table2
         on t1.ID equals new { ID = (from t2a in ctxt.Table2
                                     where t2a.ID == 281026 
                                     select t2a.ID) }
select t1;

然而我得到的错误是:

The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'.

t1.ID和t2a.ID都是整数。

有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

                                 from t2a in ctxt.Table2
                                 where t2a.ID == 281026 
                                 select t2a.ID

这样做有什么意义?如果它返回任何内容,则此子查询将始终返回281026 ...

您的查询等同于:

 from t1 in ctxt.Table1
 join t2 in ctxt.Table2
     on t1.ID equals t2.ID
 where t2.ID == 281026
 select t1;

答案 1 :(得分:0)

你在找这个吗?

from t1 in ctxt.Table1
join t2 in ctxt.Table2 on t1.ID equals 
    (from t2a in ctxt.Table2 
    where t2a.ID == 281026 
    select t2a.ID)
select t1;