gpt4 book ai didi

c# - EFCore 在 dbcontext 的生命周期内使用单个 dbconnect

转载 作者:行者123 更新时间:2023-12-04 11:56:12 28 4
gpt4 key购买 nike

我正在使用 EFCore 将数据传输到后端数据库,我调用 SaveChanges对于添加到数据集中的每一定数量的新对象,我从 EFCore 调试日志中注意到,每次我调用 SaveChanges 时,它都会关闭连接并打开一个新对象。 :

Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection|DEBUG|Opening connection to database ...
Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection|DEBUG|Beginning transaction with isolation level 'Unspecified'.
Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection|DEBUG|Committing transaction
Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection|DEBUG|Closing connection to database...
.... the logs repeats forever

那么是否可以在 DbContext 的整个生命周期中只使用一个连接? ?

最佳答案

你真的不需要改变它的工作方式,甚至根本不需要担心。默认情况下,SQL Server 连接只是放回到连接池中,因此实际上它不会关闭。打开一个新的只会捕获池中的下一个可用。

如果你真的想要,你可以通过在连接字符串中设置值来控制池,而我建议不要这样做,除非你真的知道你在做什么,这些是使用的主要属性(来自 MSDN ):

Connection Lifetime: When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified by Connection Lifetime. This is useful in clustered configurations to force load balancing between a running server and a server just brought online. A value of zero (0) will cause pooled connections to have the maximum time-out.

Connection Reset: Determines whether the database connection is reset when being removed from the pool. For Microsoft SQL Server version 7.0, setting to false avoids making an additional server round trip when obtaining a connection, but you must be aware that the connection state, such as database context, is not being reset.

Enlist: When true, the pooler automatically enlists the connection in the current transaction context of the creation thread if a transaction context exists.

Max Pool Size: The maximum number of connections allowed in the pool.

Min Pool Size: The minimum number of connections maintained in the pool.

Pooling: When true, the connection is drawn from the appropriate pool, or if necessary, created and added to the appropriate pool.

关于c# - EFCore 在 dbcontext 的生命周期内使用单个 dbconnect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45329463/

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