Hi,
I have SQL 2008 server with tables Employee, Phone and Email where Employee is in a one-to-many relation with Phone and Email (So employee can have many phone numbers and emails).
Now I want to query employee with all phones and emails:
var query = (from e in db.Employee
select new EmployeeDTO
{
Id = e.Id,
Name = e.Name,
Phones = e.Phones,
Emails = e.Emails
}).ToList();
But linq translates it to very ugly sql, it makes left join with phone table but then it queries each employee emails in separate query like:
SELECT [t0].[EmployeeID], [t0].[Name], [t1].[Phone] (
SELECT COUNT(*)
FROM [dbo].[Phone] AS [t2]
WHERE [t2].[EmployeeID] = [t0].[EmployeeID]
) AS [value]
FROM [dbo].[Employee] AS [t0]
LEFT OUTER JOIN [dbo].[Phone] AS [t1] ON [t1].[EmployeeID] = [t0].[EmployeeID]
ORDER BY [t0].[EmployeeID], [t1].[PhoneID]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.4926
SELECT [t0].[EmailID], [t0].[Email]
FROM [dbo].[Email] AS [t0]
WHERE [t0].[EmployeeID] = @x1
-- @x1: Input UniqueIdentifier (Size = 0; Prec = 0; Scale = 0) [1ed2e9a0-ca4b-4912-8f8e-000ed8d0b2af]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.4926
SELECT [t0].[EmailID], [t0].[Email]
FROM [dbo].[Email] AS [t0]
WHERE [t0].[EmployeeID]= @x1
-- @x1: Input UniqueIdentifier (Size = 0; Prec = 0; Scale = 0) [2203192b-05ef-4b59-b4b4-0010e26a8119]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.4926
What I need is simple sql:
SELECT [t0].[EmployeeID], [t0].[Name], [t1].[Phone], [t2].[Email]
FROM [dbo].[Employee] AS [t0]
LEFT OUTER JOIN [dbo].[Phone] AS [t1] ON [t1].[EmployeeID] = [t0].[EmployeeID]
LEFT OUTER JOIN [dbo].[Email] AS [t2] ON [t2].[EmployeeID] = [t0].[EmployeeID]
How can I write such linq query without grouping the results? I know how to make multiple left join, but then I need to group the results by EmployeeID.