3

In entity framework, the DbContext class implements IObjectContextAdapter interface. When I look inside this interface I see there's only one property

ObjectContext ObjectContext {get;}

But DbContext class itself doesn't have that property. Now:

  1. How does it work? Shouldn't compiler force the DbContext class to have public ObjectContext property?
  2. Or put it another way: Why do I have to cast DbContext to ObjectContextAdapter to get access to ObjectContext property.

What's going on here?

Mikayil Abdullayev
  • 12,117
  • 26
  • 122
  • 206

1 Answers1

4

This is an example of explicit interface implementation.

So to theoretically understand it see this example

interface IExplicit
{
    void Explicit();
}

class Test : IExplicit
{
    void IExplicit.Explicit()
    {
     //some implementation goes here
    }
}

Now we can instantiate a new Test(), but to access the IExplicit implementation we have to cast the type like

var testobj = new Test();

**will throw Compile time error.
testobj.Explicit();

**We can do.
((IExplicit)testobj).Explicit();

so now coming to your actual implementation of dbcontext

DbContext implemented that property explicitly.So instance will have to be casted to its interface in order to be accessible.

public class DbContext : IObjectContextAdapter
{
    ObjectContext IObjectContextAdapter.ObjectContext 
    {
     get
        { 
         ... 
        }
    }
}

You can find the explicit interface documentation here on msdn.

Navoneel Talukdar
  • 4,393
  • 5
  • 21
  • 42