gpt4 book ai didi

c# - 如何将 IDbConnection 传递给 EF 上下文?

转载 作者:太空狗 更新时间:2023-10-29 19:42:33 25 4
gpt4 key购买 nike

Entity Framework cotext DbContext 具有采用 DbConnection 的构造函数。为什么不是 IDbConnection?

是否通常将 DbConnection 传递给 EF 上下文而不是使用默认构造函数(从 App.config 读取连接字符串?)

最佳答案

Entity Framework cotext DbContext has constructor which takes DbConnection. Why not IDbConnection?

因为我不是 EF 团队的一员,所以我不能代表他们说什么。在我看来,它像 DbConnection,因为抽象基础已经为您提供了一些实现,所以您任何重写的类都可以“免费”获得东西。

我找到了一个不错的答案 here :

One of the main benefits has to do with versioning. As Microsoft adds new functionality to the providers they need to expose this functionality to the developer.

Using the old interface only approach, they would have to change the interface ( but they wouldn't because interfaces are immutable ) and all class implementing the interface in the framework. Any custom classes written by Developers implementing the interface would also need to be modified to implement any changes to the interface. If they keep adding new features ( which they will ), this becomes a vicious cycle of needing to change interfaces or implementing new ones to offer new functionality.


Is it normally to pass DbConnection to EF context instead of using default constructor?

docs很清楚你为什么要使用这个重载:

Constructs a new context instance using the existing connection to connect to a database. The connection will not be disposed when the context is disposed if contextOwnsConnection is false.

如果您已经有一个开放的上下文并且想传递它,您可以这样做。 “是否正常” 会因用例而异。我自己根本没有使用过这个重载。

关于c# - 如何将 IDbConnection 传递给 EF 上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29591646/

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