I want to know a query in linq which is equivalent to below:
select t1.*, (select columname from table2 t2 where id = 2)
from table1 t1
I want to know a query in linq which is equivalent to below:
select t1.*, (select columname from table2 t2 where id = 2)
from table1 t1
Following my SQL to LINQ Recipe, but with a slight twist for the sub-query being in the select:
var ans = from t1 in table
select new {
t1,
columnname = (from t2 in table2
where id == 2
select columnname).FirstOrDefault()
};
Note this will be sent to SQL as one query. This is one case where putting the sub-query in another variable will cause LINQ to send two SQL queries instead. SQL requires an (implied) First
on the sub-query, but you could leave it off if you don't mind columnname
being an IEnumerable
that potentially has multiple values.