gpt4 book ai didi

c# - Entity Framework 核心 : LINQ advise needed on better approach using include for relational tables

转载 作者:行者123 更新时间:2023-12-04 13:09:22 25 4
gpt4 key购买 nike

我有一个关于 Entity Framework Core 和使用 LINQ 的问题。我想在访问 Clients 时获取其他表的详细信息 table 。我可以使用以下代码获取它们。我总共需要加入大约 10 个表,在这种情况下,下面的方法是好的还是其他更好的方法? ClientId是所有表的外键。
实际上我收到如下警告

[09:34:33 Warning] Microsoft.EntityFrameworkCore.QueryCompiling a query which loads related collections for more than one collection navigation either via 'Include' or through projection but no 'QuerySplittingBehavior' has been configured. By default Entity Framework will use 'QuerySplittingBehavior.SingleQuery' which can potentially result in slow query performance. See https://go.microsoft.com/fwlink/?linkid=2134277 for more information. To identify the query that's triggering this warning call 'ConfigureWarnings(w => w.Throw(RelationalEventId.MultipleCollectionIncludeWarning))'


代码:
var client = await _context.Clients
.Include(x => x.Address)
.Include(x => x.Properties)
.Include(x => x.ClientDetails)
-------------------
-------------------
-------------------
-------------------
.Where(x => x.Enabled == activeOnly && x.Id == Id).FirstOrDefaultAsync();

最佳答案

实际上,当您使用 Eager loading(使用 include() )时,它使用左连接(一个查询中所有需要的查询)来获取数据。它默认为 ef 5 中的 ef 行为。
您可以设置 AsSplitQuery()在您的 split all 查询中,包含在单独的查询中。喜欢:

var client = await _context.Clients
.Include(x => x.Address)
.Include(x => x.Properties)
.Include(x => x.ClientDetails)
-------------------
-------------------
-------------------
-------------------
.Where(x =>x.Id == Id).AsSplitQuery().FirstOrDefaultAsync()
这种方法需要更多的数据库连接,但这并不重要。
对于最后的建议,我建议使用 AsNoTracking()用于高性能查询。

关于c# - Entity Framework 核心 : LINQ advise needed on better approach using include for relational tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67275869/

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