views:

294

answers:

3

How to I convert the following SQL statement into LinqToSQL?

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

My attempts seem to end up doing an inner join (and therefore giving wildly inaccurate results).

Thanks

A: 

Edit2:

Try this instead, fixed the Key issue in the first query, and the second one now creates a correct empty result.

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 };
Yannick M.
It's close, but this only returns rows from t1 where an associated records exists in t2, whereas the SQL statement in the question contains all entries from t1.
I had to amend subQuery to include an extra from clause, after the group statement. Once this is done, the code compiles, but throws an InvalidOperationException when executing the second query (it's attempting to assign null to an Int32).
The query compiles, but attempting to access any methods on the result set generates a NotSupportedException: Unsupported overload used for query operator 'DefaultIfEmpty'.
+2  A: 

If relationships are present in your database, you can use a pretty simple query similar to the following:

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

If relationships are not present, this should work:

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()
              };
Ryan Versaw
I also checked the generated Sql (in LinqPad) and it should be almost identical to the Sql you were hoping to duplicate.
Ryan Versaw
Thanks - thats as easy (and obvious) as I thought it should be!
A: 
var result = db.table1s.select(t => new {.Name = t.Name, .Count = t.table2s.Count()});
Shawn Simon