使用 DbConnection 初始化 EF Core DbContext 连接

Initialize EF Core DbContext connection with DbConnection

我正在将 EF6 .net fwk 应用程序迁移到 Entity Framework Core 3.0。但是,在我的旧 EF6 项目中,我可以选择使用 DbConnection 对象初始化 DbContext,用于实现工作单元并使用相同的事务而不更改连接对象。

public MyDataContext(IDbConnection connection)
        : base((DbConnection) connection, false)
    {
    } 

但是,在 EF 核心中,我只有一个选项可以使用 DbContextOptions 初始化上下文,它需要一个连接字符串。这将初始化新连接,我将无法处理事务。

旧 EF 代码

var pipeline = endpointConfiguration.Pipeline;
        pipeline.Register(new UnitOfWorkSetupBehavior(storageSession =>
        {
            var dbConnection = storageSession.SqlPersistenceSession().Connection;
            var context = ***new MyDataContext(dbConnection);***
            context.Database.UseTransaction(storageSession.SqlPersistenceSession().Transaction);
            storageSession.SqlPersistenceSession().OnSaveChanges(x => context.SaveChangesAsync());

            return context;
        }), "Setting up unit of work");

带连接对象的构造函数的替代方案是什么,或者 EF 核心 DBcontext 中真正改变了什么不接受连接?

在 .Net 核心中,Dependency injection became a corner stone in the framework, so, now you shouldn't be initializing the DBContext yourself, you instead should leave it to the container, which by default initialize it with a "scoped liftime",因此在整个请求中,它会将相同的 DbContext 传递给您的服务,因此应该出现一次故障(如果您做对了,请调用仅在最后保存一次更改)回滚所有更改。