简体   繁体   English

如果DbContext是从ObjectContext创建的,我是否需要处置它?

[英]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. 我做了一些扩展方法来计数相关记录,但我不想显式传递DbContext,所以我改用ObjectContext并从中创建一个DbContext。

Will the new DbContext get disposed when the original DbContext is dispose? 处置原始DbContext时是否会处置新的DbContext?

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. 经过更多的研究,测试和检查DbContext的源代码后,我得出了不需要的结论。 The DbContext only needs to dispose of the internal context which is a wrapper for the ObjectContext that is passed. DbContext仅需要处理内部上下文,该内部上下文是所传递的ObjectContext的包装。

If you dispose of the DbContext that owns the ObjectContext, the new DbContext will essentially be disposed. 如果处置拥有ObjectContext的DbContext,则实际上将处置新的DbContext。

Constructing a new DbContext from object context. 从对象上下文构造一个新的DbContext。 When setting the dbContextOwnsObjectContext to 'true' the ObjectContext is disposed when the DbContext is disposed, otherwise the caller must dispose the connection. 当将dbContextOwnsObjectContext设置为“ true”时,将在处理DbContext时处理ObjectContext,否则调用者必须处理连接。

By setting it to false as you have, the new DbContext would not be disposed 通过将其设置为false,将不会处理新的DbContext

EDIT 编辑

This spools up that objectContext separately from the dbContexts 这使该对象上下文与dbContexts分开进行处理

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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