1

我有一个车辆表,我需要对 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 });

到目前为止,一切都很好。VehicleAttribute 还有一列 AttributeId。我只需要在此列表中加入这些 VehicleAttributes :

List<Guid> allowedAttributes = (from ua in context.UserAttributes
                                                    where ua.UserId == UserSession.CurrentUser.UserId
                                                    select ua.AttributeId).ToList();

我该怎么做?我认为子查询可能是正确的方法,但我很挣扎..

感谢所有的答案。

编辑:解释我的问题的另一种方法:我有这两个查询

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'

并想将它们组合起来,所以我只得到第二个查询中的属性 id。where 子句不起作用,因为即使没有 attributeIds 我仍然想要 vehicleId

4

2 回答 2

1

定义后,allowedAttributes您可以更改

vAttributes.DefaultIfEmpty()

您的第一个查询:

vAttributes
    .Where(va => allowedAttributes.Contains(va.AttributeId))
    .DefaultIfEmpty()
于 2013-06-04T21:02:07.123 回答
0

不确定这是您的情况。您可以尝试使用子查询进行左连接:

//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 });
于 2013-06-04T18:54:27.797 回答