【发布时间】:2021-12-09 14:18:10
【问题描述】:
我有一个 LINQ 查询的情况。它有两个连接(一对多),但它带回了连接表中的所有列。我不确定如何创建 LINQ 查询以仅返回连接表中的几个字段。
var data = from mc in ctx.MembershipChapters
where mc.PartitionKey == controllerStateManager.PartitionKey && mc.MembershipId == membershipId
join prd in ctx.Products on mc.ProductId
equals prd.Id into prods
from prd in prods.DefaultIfEmpty()
join oli in ctx.OrderLineItems on mc.OrderLineItemId equals oli.OrderLineItemId into olis
from oli in olis.DefaultIfEmpty()
select new
{
MembershipName = mc.Membership.Name,
Products = prods.Select(p => new {
ProductName = p.Name, ProductId = p.Id }),
OrderLineItems = olis.Select(o => new { OrderLineItemName = o.Description, OrderLineItemId = o.OrderLineItemId })
};
controllerStateManager.Data = data.ToList();
这不起作用...我收到一个错误:“o”不在范围内。
基本上输出应该是这样的:
会员章节 ---> OrderLineItems ----------> 产品
我是 LINQ 的新手,我已经为此苦苦挣扎了太久。
【问题讨论】:
-
您好,您的别名重复 oli/prd 并且连接顺序对我不利,我会这样写:from mc in ctx.MembershipChapters where mc.PartitionKey == controllerStateManager. PartitionKey && mc.MembershipId ==membershipId 在 mc.ProductId 上的 ctx.Products 中加入 prd 等于 prd.Id 进入 prods 在 mc.OrderLineItemId 上的 ctx.OrderLineItems 中加入 oli 等于 oli.OrderLineItemId 在 prods 中从 prd2 进入 olis.DefaultIfEmpty() 从 oli2在 olis.DefaultIfEmpty()
标签: c# linq join select multiple-columns