Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When exactly is the "first time" a DbContext accesses the database?

We're trying to figure out when exactly an Entity Framework Database Initializer runs.

MSDN says initializion happens the "first time" we access the database. When is "first time"?

MSDN contradicts itself, stating that initialization runs the first time an instance of a DbContext is used but also the first time a type of a DbContext is used. Which is it?

Further, MSDN doesn't define "first time"? Is this first time since publish? first time since Application_Start? first time for a given request, for a given method? What if we restart the application by changing the web.config?

Here are some quotes from MSDN, saying database initializer runs...

when an instance of a DBContext derived class is used for the first time

http://msdn.microsoft.com/en-us/library/gg696323%28v=vs.113%29.aspx

when the given DbContext type is used to access a database for the first time

http://msdn.microsoft.com/en-us/library/gg679461%28v=vs.113%29.aspx

For example, we have a controller action, in which we instantiate a DbContext and run an insert operation. If we call this action twice (or 10,000 times), will the DbInitializer run that many times? If we're using the DropDatabaseCreateAlways initializer, and we call this action twice, will the Db have two Event rows, or will the initializer delete the Db between inserts, thereby leaving one Event row?

public HttpResponseMessage PostEvent(EventDTO eventDTO)
{
    var ev = new Event()
    {
        Id = eventDTO.Id,
        Name = eventDTO.Name
    };

    using (AttendanceContext db = new AttendanceContext())
    {
        db.Events.Add(ev);
        db.SaveChanges();
    }

    return Ok();
}
like image 767
Shaun Luttin Avatar asked Oct 22 '14 15:10

Shaun Luttin


1 Answers

Entity Framework initializes the databse once per AppDomain startup.

When the DbContext class is first instantiated by your code, and one of it's properties are accessed, it uses an InternalContext instance that handles the initialization logic, and ensures that said initialization runs only once, using a static class field.

If you make a change on the web.config file, or when the application pool recycles or the iis process itself is restarted, your application domain will be started again and the initializer will fire. This post should help in knowing when this happens in web applications.

Reusing the same context instance multiple times, or even creating a new context on each request, will not trigger initialization each time.

like image 147
julealgon Avatar answered Sep 29 '22 03:09

julealgon