簡體   English   中英

Linq離開了實體框架

[英]Linq left join with Entity Framework

我有一個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 });

到現在為止還挺好。 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

定義allowedAttributes您可以更改

vAttributes.DefaultIfEmpty()

您的第一個查詢:

vAttributes
    .Where(va => allowedAttributes.Contains(va.AttributeId))
    .DefaultIfEmpty()

不確定這是您的情況。 您可以嘗試使用子查詢向左聯接:

//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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM