使用Linq查询1-n导航路径的数据

时间:2017-01-02 13:18:48

标签: c# linq

我的表中有以下关系。

TravelPlan (Table A)

Destination(table D)Users(table E)用于构建旅行选择,即Travelplan中的条目可以包含多个DestinationUser(映射存储在另一个映射表,即1到n)

DestinationTravelPlanMapping(TableC) UserTravelPlanMapping(TableD)

但我无法完成查询。这个

有什么问题

我需要使用Linq为给定用户提取所有Unique destinations

 var userId=6;
return context.TravelPlan
                        .Include(x => x.DestinationTravelPlanMapping)
                        .Include(x => x.DestinationTravelPlanMapping.Select(y => y.Destination))
                        .Include(x => x.UserTravelPlanMapping.Select(y => y.UserId == userId))
// the below select statement is throwing error
                        .Select(x => x.DestinationTravelPlanMapping.Select(y => new Destination
                        {
                            Id = y.Destination.Id,
                            Name = y.Destination.Name
                        }));

1 个答案:

答案 0 :(得分:0)

试试这个:

return context.TravelPlans
    .Where(x => x.UserTravelPlanMapping.Any(y => y.UserID == userID))
    .SelectMany(x => x.DestinationTravelPlanMapping.Select(y => y.Destination))
    .Distinct();

您希望DestinationTravelPlans的唯一UserTravelPlanMappingUserIDuserID匹配变量{{1}}。