[英]Linq left join with Entity Framework
I have a table of Vehicles and I need to do a left join on VehicleAttribute. 我有一个Vehicles表,我需要对VehicleAttribute进行左连接。
var vehicle = (from v in context.Vehicles
//join vehicleAttributes
join va in context.VehicleAttributes on v.VehicleId equals va.VehicleId into vAttributes
from vehicleAttributes in vAttributes.DefaultIfEmpty()
where v.VehicleId == vehicleId
select new { v, vehicleAttributes });
so far so good. 到现在为止还挺好。 VehicleAttribute has also a column AttributeId.
VehicleAttribute还具有一列AttributeId。 And I only need to join those VehicleAttributes when it's in this List:
我只需要在此列表中加入这些VehicleAttributes:
List<Guid> allowedAttributes = (from ua in context.UserAttributes
where ua.UserId == UserSession.CurrentUser.UserId
select ua.AttributeId).ToList();
How would I do that? 我该怎么做? I think a subquery might be the right approach but I'm struggling..
我认为子查询可能是正确的方法,但我正在努力。
Thanks for all answers. 感谢所有答案。
EDIT: A different approach to explain my problem: I have these two queries 编辑:一种不同的方法来解释我的问题:我有这两个查询
SELECT Vehicle.VehicleId,VehicleAttribute.AttributeId
FROM Vehicle
LEFT JOIN VehicleAttribute
ON Vehicle.VehicleId = VehicleAttribute.VehicleId
SELECT UserAttribute.AttributeId
FROM UserAttribute
WHERE UserAttribute.UserId = '4D0F8AD2-7A4D-4E29-A6D3-E5FCD6075388'
and want to combine them so I only get the attribute id's which are in the second query. 并希望将它们组合在一起,因此我只获得第二个查询中的属性ID。 A where clause doesn't work because I still want the vehicleId even if there are no attributeIds
where子句不起作用,因为即使没有attributeIds,我仍然想要vehicleId
After you defined allowedAttributes
you can change 定义
allowedAttributes
您可以更改
vAttributes.DefaultIfEmpty()
of your first query to: 您的第一个查询:
vAttributes
.Where(va => allowedAttributes.Contains(va.AttributeId))
.DefaultIfEmpty()
Not sure this is your scenario. 不确定这是您的情况。 You could try to Left join with a subquery:
您可以尝试使用子查询向左联接:
//define the query that returns allowed VehicleAttributes
allowedAttributesQuery =from ua in context.UserAttributes
where ua.UserId == UserSession.CurrentUser.UserId
select ua.VehicleAttribute; //I suppose that VehicleAttribute navigation property exists in the UserAttribute
//query that joins Vehicles with the allowedAttributes subquery
var vehicle = (from v in context.Vehicles
join va in allowedAttributesQuery on v.VehicleId equals va.VehicleId into vAttributes
from vehicleAttributes in vAttributes.DefaultIfEmpty()
where v.VehicleId == vehicleId
select new { v, vehicleAttributes });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.