How do I join on a constant in LINQ?
I'm trying to do a left join on a constant like this:
SELECT
[t0].[DeviceId],
[t0].[DeviceTypeId],
[t0].[UnitId],
[t0].[UnitNum],
[t0].[ManPhone],开发者_JS百科
[t0].[Status],
[t2].[MaintDate] AS [ServiceExpiration]
FROM [dbo].[Devices] AS [t0]
INNER JOIN [dbo].[CustomerDevices] AS [t1]
ON ([t0].[DeviceId]) = [t1].[DeviceId]
LEFT JOIN [dbo].[Maintenance] AS [t2]
ON ([t0].[DeviceId]) = [t2].[DeviceId]
AND 8 = [t2].ActionId
I get a CS1941 when I attempt it in LINQ like this:
var devices = from d in db.Devices
join cd in db.CustomerDevices
on d.DeviceId equals cd.DeviceId
join serviceExpiration in db.Maintenances
on
new { d.DeviceId, ActionId = 8 } // CS1941
equals
new { serviceExpiration.DeviceId, ActionId = serviceExpiration.ActionId } into j1
from deviceServiceExpiration in j1.DefaultIfEmpty()
Try from Maintenances on ActionId == 8
first, then use this to join against.
var expirations = from serviceExpiration in db.Maintenances
where serviceExpiration.ActionId == 8
select serviceExpiration;
var devices = from d in db.Devices
join cd in db.CustomerDevices
on d.DeviceId equals cd.DeviceId
join e in expirations
on d.DeviceId = e.DeviceId into j1
from deviceServiceExpiration in j1.DefaultIfEmpty()
select deviceServiceExpiration;
Try this
var devices = from d in db.Devices
join cd in db.CustomerDevices
on d.DeviceId equals cd.DeviceId
join serviceExpiration in db.Maintenances
on d.DeviceId equals serviceExpiration.DeviceId into j1
from deviceServiceExpiration in j1.Where(c=>c.ActionId ==8).DefaultIfEmpty()
Late to the party here, but I ran into the same issue and wanted to help anyone in the future. The fix is to join to a sub-query.
var devices = from d in db.Devices
join cd in db.CustomerDevices
on d.DeviceId equals cd.DeviceId
join serviceExpiration in (from x in db.Maintenances where x.ActionId == 8 select x)
on d.DeviceId equals serviceExpiration.DeviceId into j1
from deviceServiceExpiration in j1.DefaultIfEmpty()
Hope this helps someone.
or within the query:
var devices = from d in db.Devices
join cd in db.CustomerDevices
on d.DeviceId equals cd.DeviceId
join serviceExpiration in db.Maintenances
on
d.DeviceId
equals
serviceExpiration.DeviceId into j1
from deviceServiceExpiration in j1.DefaultIfEmpty()
where serviceExpiration.ActionId == 8
select deviceServiceExpiration;
精彩评论