将sql查询转换为Linq或lambda

时间:2016-01-11 05:02:58

标签: sql linq lambda

我在sql server中有以下查询:

select * from
A as a where a.UserId in(select b.id from  B as b) and a.Company is null 

任何人都可以帮我写linq或Lambda表达。感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

你可以使用Contains,它不会生成一个IN子查询而是一个EXIST子查询,但它将非常接近你的原始SQL

var q1 = context.B
    .Select(item=>item.Id);

var q2 = context.A
    .Where(a=>q1.Contains(a.UserId))
    .Where(a=>a.Company == null); // Calling where twice for readability, will generate the same SQL as if you had both weres on a single line with AND, no performance overhead for doing so

或者,如果您更愿意将其写入一个块(将生成相同的SQL)

var q2 = context.A
    .Where(a=>context.B
          .Select(item=>item.Id).Contains(a.UserId))
    .Where(a=>a.Company == null);

答案 1 :(得分:0)

使用联接

var t = (from a in entites.b.ToList()
         from b in entites.a.where(x=>x.UserId ==a.id && x.Company==null).ToList()
         select b).ToList();

答案 2 :(得分:0)

var x= (from a in db.Table1 
        join b in dbTable2 on a.UserId equals b.id
        where a.Company == null
        select a).ToList();