0
votes

I am migrating EF6 .net fwk application to Entity Framework Core 3.0. however, in my old EF6 project i had an option to initialize DbContext using a DbConnection Object, was used for implementing unit of work and use same transaction without changing the connection object.

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

however, in EF core i have only one option to initialize the context that with a DbContextOptions, that takes a connection string. and this will initialize new connection , and I wont be able to work with transaction.

OLD EF code

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");

Whats the alternative for the constructor with connection object, or what really changed in the EF core DBcontext not to take the connection ?

1

1 Answers

3
votes

In .Net core, 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", thus throughout one request, it'll be passing the same DbContext to your services and thus a single failure should (if you're doing it right, call the save changes only once at the very end) rollback all the changes.