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();
}