将SQL转换为linq-to-sql(子查询)

时间:2009-10-08 07:25:35

标签: sql linq-to-sql

如何将以下SQL语句转换为LinqToSQL?

select t1.name, (select COUNT(*) from table2 where t2.f_id = t1.id) as cnt
from table1 t1

我的尝试似乎最终会进行内部联接(因此会产生非常不准确的结果)。

由于

3 个答案:

答案 0 :(得分:3)

如果数据库中存在关系,则可以使用类似于以下内容的非常简单的查询:

var results = from t1 in context.Table1
              select new
              {
                  t1.Name,
                  T2Count = t1.Table2s.Count()
              };

如果没有关系,这应该有效:

var results = from t1 in context.Table1
              join t2 in context.Table2 on t1.id equals t2.f_id into joined
              select new
              {
                  t1.Name,
                  T2Count = joined.Count()
              };

答案 1 :(得分:0)

EDIT2:

尝试使用此功能,修复了第一个查询中的密钥问题,第二个现在创建了正确的空结果。

var subQuery = from t2 in DataContext.Table2
               group t2 by t2.f_Id into myGroup
               select new { Id = myGroup.Key, Cnt = myGroup.Count() };


var result = from t1 in DataContext.Table1
             join t2 in subQuery on t1.Id equals t2.Id into temp
             from t3 in temp.DefaultIfEmpty(new { Id = t1.Id, Cnt = 0 })
             select new { t1.Name, t3.Cnt };

答案 2 :(得分:0)

var result = db.table1s.select(t => new {.Name = t.Name, .Count = t.table2s.Count()});