I’m trying to convert this SQL into a Linq2SQL query, however, I’m at the point of just dragging a stored procedure into the dbml and hoped someone could do a better job. When there are no records for the nested query, it is returning null.
SQL:
SELECT
Table1.Field1 -
ISNULL(
(
SELECT
SUM(Table2.Field1)
FROM Table2
INNER JOIN Table3 ON Table2.ID = Table3.Table2ID
WHERE Table3.Table1ID = Table1.ID
)
,0)
FROM
Table1
WHERE
(Table1.ID = @ID)
Linq2SQL
return (from q in db.Table1s
where q.ID == id
select q.Field1.GetValueOrDefault() -
(from o in db.Table2s
join r in db.Table3s on o.ID equals r.Table2ID.GetValueOrDefault(0)
where r.Table1ID == q.ID
select Convert.ToInt32(o.Field1.GetValueOrDefault(0))).Sum()
).SingleOrDefault()
Can anyone do a better job.
A concise version using method syntax and lambda expressions:
A more readable version using query syntax with a let statement:
I strongly recommend using a tool like LinqPad to design your queries, because it will show you the SQL that is generated. This allows you to tune your more expensive queries for better results.
Its also useful for quick prototyping and testing of short blocks of code.