在linq中翻译t-sql

时间:2010-11-09 15:41:43

标签: linq

如何在Linq中编写以下t-sql?

select (select COUNT(col1) FROM t2 WHERE col2 = t1.col2 and col1 = t1.col1) as total,

 t1.col1,t1.col2...................

from t1 

2 个答案:

答案 0 :(得分:0)

var res = from t1 in context.t1s
    select new
    {
        total = context.t2s.Where(t2=> t2.col1 == t1.col1 && t2.col2 == t1.col2).Count(),
        t1.col1,
        t1.col2,
    };

修改
如果您在数据库和DBML中正确设置了FK关系,则可以使用下面更简单的版本

var res = from t1 in context.t1s
    select new
    {
        total = t1.t2s.Count(),
        t1.col1,
        t1.col2,
    };

答案 1 :(得分:0)

尝试使用LinqPad。它非常适合在SQL和LINQ查询之间进行转换。

http://www.linqpad.net/