简体   繁体   中英

Do I need to dispose of a DbContext if it was created from an ObjectContext?

I made some extension methods for counting related records and I don't want to explicitly pass the DbContext, so instead I get the ObjectContext and create a DbContext from it.

Will the new DbContext get disposed when the original DbContext is dispose?

var original = new CustomDbContext("connectionString")
var entity = original.Table.First()

// in the extension method
var objectContext = entity.GetObjectContext()
var newDbContext = new CustomDbContext(objectContext, false)
// dispose of newDbContext??

// original caller
original.Dispose()

After some more researching, testing and checking the source code for DbContext I came to the conclusion that is not required. The DbContext only needs to dispose of the internal context which is a wrapper for the ObjectContext that is passed.

If you dispose of the DbContext that owns the ObjectContext, the new DbContext will essentially be disposed.

Constructing a new DbContext from object context. When setting the dbContextOwnsObjectContext to 'true' the ObjectContext is disposed when the DbContext is disposed, otherwise the caller must dispose the connection.

By setting it to false as you have, the new DbContext would not be disposed

EDIT

This spools up that objectContext separately from the dbContexts

        var objectContext = new ObjectContext("connectionString");
        var newDbContext1 = new CustomDbContext(objectContext, false);
        var newDbContext2 = new CustomDbContext(objectContext, false);

        newDbContext1.Dispose();
        newDbContext2.Dispose();
        objectContext.Dispose();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM