Alireza
Alireza

Reputation: 10476

How DbContext initializes automatic DbSet<T> properties?

Consider the following class:

class MyContext : DbContext
{
    public DbSet<Order> Orders { get; set; }
}

and instantiating a new object:

var mycontext = new MyContext();

Why mycontext.Orders is not null? When it was initialized? Who has initialized it? I'm really confused because the base class (DbConetxt) cannot access the derived class properties so it is not possible that the automatic property was initialized in the base object.

Upvotes: 6

Views: 2289

Answers (1)

Matt Whetton
Matt Whetton

Reputation: 6786

From looking at the reflected code, when the DbContext (the base class) is constructed it makes a call to the DbSetDiscoveryService (an internal clasS) - which essentially uses reflection to find all properties on the DbContext, and then initializes those that need initializing.

So in short - using reflection in the constructor.

Upvotes: 8

Related Questions