3

I have the following code in Entity Framework:

using(var dbc = new TestDbContext())
{
    var data = (from a in dbc.tableList
                select new { a = id }).ToList();
}

When I was debugging the code I came across the following piece of code

public class TestDbContext : DbContext
{
     public TestDbContext()
     { 
     }

     public DbSet<Table> tableList {get;set;}
}

I am wondering like without even creating an instance of DbSet<Table> like this :

public Dbset<Table> tableList = new Dbset<Table>();

how am I able to query the table for eg:

in

var data = (from a in dbc.tableList
            select new { a = id }).ToList();
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
user2630764
  • 624
  • 1
  • 8
  • 19

3 Answers3

6

There's no magic to this. TestDbContext is derived from DbContext

DbContext makes a call to internal class DbSetDiscoveryService which uses Reflection to iterate through DbSet properties and initialize them.

The mono version of EF, you can find the code on Github that shows the call to InitializeSets

GeekzSG
  • 943
  • 1
  • 11
  • 28
4

During construction, EF will scan a DbContext derived object for any DbSet properties and initialize it accordingly via reflection.

From the Remarks section on DbContext documentation.

DbContext is usually used with a derived type that contains DbSet<TEntity> properties for the root entities of the model. These sets are automatically initialized when the instance of the derived class is created. This behavior can be modified by applying the SuppressDbSetInitializationAttribute attribute to either the entire derived context class, or to individual properties on the class.


If you're wondering how it works, you can see the source here:

  1. http://entityframework.codeplex.com/SourceControl/latest#src/EntityFramework/DbContext.cs
  2. http://entityframework.codeplex.com/SourceControl/latest#src/EntityFramework/Internal/DbSetDiscoveryService.cs
IronGeek
  • 4,764
  • 25
  • 27
2

You TestDbContext inherited from DbContext. I think, may be inside DbContext constructor via reflection all field like DbSet<Table> are initialized.

Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26