Reputation: 618
I have a table of Vehicles and I need to do a left join on 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. And I only need to join those VehicleAttributes when it's in this List:
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. A where clause doesn't work because I still want the vehicleId even if there are no attributeIds
Upvotes: 1
Views: 4675
Reputation: 6445
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 });
Upvotes: 0
Reputation: 4198
After you defined allowedAttributes
you can change
vAttributes.DefaultIfEmpty()
of your first query to:
vAttributes
.Where(va => allowedAttributes.Contains(va.AttributeId))
.DefaultIfEmpty()
Upvotes: 1