gpt4 book ai didi

c# - 正确的 Join/GroupJoin 实现

转载 作者:行者123 更新时间:2023-11-30 15:46:48 26 4
gpt4 key购买 nike

我一直在尝试使用 Join 和 GroupJoin 方法。问题看起来很简单。给定 TableATableB 作为数据映射,这样:

class MyDataContext : DataContext
{
public Table<tblA> TableA;
public Table<tblB> TableB;
}

...我正在使用 TableA 作为我的主表,并希望加入 TableB 中的一个字段 CustomerID 以检索 [TableB].[姓氏]

应该不难,只是我很难让结果正常工作。 TableA 有我想要的记录,而不管 TableB 中是否有匹配的 CustomerID。听起来像左连接 - 所以,阅读 here ,我模仿了@tvanfosson 的建议:

// appropriately rewritten for my needs - so I thought...
private static IQueryable GetRecordsByView1(IQueryable<tblA> source)
{
var records = source.GroupJoin(myContext.TableB,
info => info.CustomerID,
owner => owner.CustomerID,
(info, owner) => new
{
info.CustomerID,
Owner = owner.Select(o => o.LastName).DefaultIfEmpty(),
Store = info.Store,
})
.Select(record => new
{
record.CustomerID,
record.Owner,
record.Store,
});

return records;
}

source 是动态的,因此一个方法构建了一个动态查询:

public static void QueryStores()
{
IQueryable<tblA> source = myContext.TableA;

if (criteriaA)
source = source.Where(// something);

if (criteriaB)
source = source.Where(// something);

// after processing criteria logic, determine type of view
switch (byView)
{
case View1:
{
source = GetRecordsByView1(source);
break;
}

//other case blocks
}

myGridView.DataSource = source;
}

问题:我收到以下错误:

Could not format node 'OptionalValue' for execution as SQL.

我相信它在以下代码行中:

Owner = owner.Select(o => o.LastName).DefaultIfEmpty()

我在这里做错了什么?我必须将 GroupJoin 编写为扩展方法。

最佳答案

您是正确的,Owner = owner.Select(o => o.LastName).DefaultIfEmpty() 是引起您问题的行。我想出的最好的解决方法是这样的:

var records = source.GroupJoin(myContext.TableB,
info => info.CustomerID,
owner => owner.CustomerID,
(info, owner) => new { info, owner }).ToList();
records.Select(x => new
{
x.info.CustomerID,
Owner = x.owner.First() == null ? new string[] {} : x.owner.Select(o => o.LastName).ToArray(),
Store = x.info.Store,
})
.Select(record => new
{
record.CustomerID,
record.Owner,
record.Store,
});

这当然不理想(您必须使用“ToList”来具体化 groupjoin),并且可能有更好的解决方案,但这对我有用。您可能需要尝试一下才能让它适合您,但我希望这对您有所帮助。

关于c# - 正确的 Join/GroupJoin 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4114110/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com