C# Linq与实体框架的左连接
我有一个车辆表,我需要在VehicleAttribute上执行左联接C# Linq与实体框架的左连接,c#,linq,entity-framework,C#,Linq,Entity Framework,我有一个车辆表,我需要在VehicleAttribute上执行左联接 var vehicle = (from v in context.Vehicles //join vehicleAttributes join va in context.VehicleAttributes on v.VehicleId equals va.VehicleId into vAttribut
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。我只需要加入以下列表中的车辆属性:
List<Guid> allowedAttributes = (from ua in context.UserAttributes
where ua.UserId == UserSession.CurrentUser.UserId
select ua.AttributeId).ToList();
并希望将它们组合在一起,以便只获取第二个查询中的属性id。
where子句不起作用,因为即使没有AttributeID,我仍然需要vehicleId。不确定这是您的场景。您可以尝试使用子查询进行左联接:
//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 });
不确定这是你的情况。您可以尝试使用子查询进行左联接:
//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 });
定义
allowedAttributes
后,可以更改
vAttributes.DefaultIfEmpty()
您第一次查询的目标:
vAttributes
.Where(va => allowedAttributes.Contains(va.AttributeId))
.DefaultIfEmpty()
定义
allowedAttributes
后,可以更改
vAttributes.DefaultIfEmpty()
您第一次查询的目标:
vAttributes
.Where(va => allowedAttributes.Contains(va.AttributeId))
.DefaultIfEmpty()
您更应该将导航属性与EF一起使用,而不是显式联接。我假设您的映射设置正确,因为这里没有显示它们……您的第一个代码段不完整,存在未定义的标识符。你能发布整个查询吗?当然我更新了我的帖子:-)你更应该使用带有EF的导航属性,而不是显式连接。我假设您的映射设置正确,因为这里没有显示它们……您的第一个代码段不完整,存在未定义的标识符。你能发布整个查询吗?当然,我更新了我的帖子:-)