当前位置:Gxlcms > 数据库问题 > DbContext 中的 Explicit interface implementation

DbContext 中的 Explicit interface implementation

时间:2021-07-01 10:21:17 帮助过:2人阅读

interface InterfaceA { void Test(); } public interface InterfaceB { void Test(); } public class RunTest : InterfaceA, InterfaceB { void InterfaceB.Test() { throw new NotImplementedException(); } void InterfaceA.Test() { throw new NotImplementedException(); } }

以这种方式实现后,实现类的实例是不能直接方法成员方法的。

DbContext 实现 IObjectContextAdapter

通过ILSpy反编译EntityFramwork.dll,并且查找DbContext后,就能看到实现IObjectContextAdapter的情况

/// <summary>
/// Returns the Entity Framework ObjectContext that is underlying this context.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">Thrown if the context has been disposed.</exception>
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
ObjectContext IObjectContextAdapter.ObjectContext
{
    get
    {
        this.InternalContext.ForceOSpaceLoadingForKnownEntityTypes();
        return this.InternalContext.ObjectContext;
    }
}

是以explicit implementation的方式实现的接口,并且不直接暴露给外部,所以这也就是为什么Entity Framework 6更希望你用DbContext这种封装了N层的类,而不希望你在通常的情况下用更底层的类,但如果要用只能通过IObjectContextAdapter本身来调用这个成员。

DbContext 中的 Explicit interface implementation

标签:

人气教程排行