Reputation: 33
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()
Upvotes: 1
Views: 200
Reputation: 284
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();
Upvotes: 0
Reputation: 33
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.
Upvotes: 1