将t-sql查询转换为linq

时间:2013-06-11 09:00:45

标签: c# sql linq tsql sql-to-linq-conversion

我有这个t-sql查询,我需要将其转换为linq

SELECT m.field1
            FROM table1 m
            Join table2 v on v.field1 = m.field1 and v.field2 = m.field3
            WHERE v.field4 =4
            AND m.field1=125325
            AND m.field5=0
            AND m.field1 IN (SELECT field1 FROM table3)

任何帮助?

2 个答案:

答案 0 :(得分:1)

只要所有表都相关,而且你不需要做LINQ的关系,所以它会是这样的:

     var result = db.table1.WHERE(p=>p.table2.field4 == 4 && p.field1 == 125325 
     && p.field5 == 0 && p.table3 != null)

db - 是DbContextObjectContext

答案 1 :(得分:1)

查询:

from m in db.table1
join v in db.table2
on new { m.field1, Field2 = m.field2 } 
equals new { v.field1, Field2 = m.field3 }
where ...
where db.table3.Select(x => x.field1).Contains(m.field1)
select m.field1;

方法链:

db.table1
    .Join(
        db.table2, 
        m => new {m.field1, Field2 = m.field2}, 
        v => new {v.field1, Field2 = m.field3},
        (m, v) => new {m, v})
    .Where(...)
    .Where(t => db.table3.Select(x => x.field1).Contains(t.m.field1))
    .Select(t => t.m.field1);