Sar*_*hrb 2 c# sql entity-framework-core asp.net-core
我想维持子孙关系。我需要区分哪些孩子返回了哪些孙子。
查询返回
"InvalidOperationException: The LINQ expression
'x =>x.Children.AsQueryable().Select(c => new
{
ItemNo= c.ItemNo,
GrandChildItemNos = c.Children.AsQueryable().Select(gc => gc.ItemNo).ToList()
})
.ToDictionary(keySelector: c => c.ItemNo, elementSelector: c => c.GrandChildItemNos)' could
not be translated. Either rewrite the query in a form that can be translated, or switch to
client evaluation explicitly by inserting a call to 'AsEnumerable',
'AsAsyncEnumerable','ToList', or 'ToListAsync'. See
https://go.microsoft.com/fwlink/?linkid=2101038 for more information."
Run Code Online (Sandbox Code Playgroud)
我认为 EF 在将 .ToDictionary() 部分转换为 SQL 时存在问题。任何人都可以帮忙解决这个问题吗?
你很接近了!
当你超越ToDictionary()具体化点(the ToListAsync())时,它就会起作用。事实上,错误消息也这么说:“或显式切换到客户端评估”。调用ToDictionary无法转换为查询。
var childDetails = await context.Items.Where(w => w.ItemNo == parentItemNo)
.SelectMany(x => x.Children
.Select(c => new
{
c.ItemNo,
GrandChildItemNos = c.Children.Select(gc => gc.ItemNo)
})
)
.ToListAsync();
var dictionary = childDetails.ToDictionary(d => d.ItemNo, d => d.GrandChildItemNos);
Run Code Online (Sandbox Code Playgroud)
这是我的结果: