SUMMARY<br /><br />You can specify a custom DbInitializer in your application's configuration to initialize your DB in some custom way. Initializer is passed a DbContext with which you can initialize the DB. <br /><br />Bug: Any changes to DbContext.Configuration in DbInitializer persists on the app code until only FIRST DbContext instance, and is reset for the following ones.<br /><br />REPRO<br /><br />1) Create a .NET 4.5 console application, add EF6 nuget package<br />2) Create a basic model and DbContext<br />3) Configure your app (through app.config or code based configuration) to use a custom DbInitializer. You can use the following:<br /><br /> public class MyInitializer : IDatabaseInitializer<MyContext><br /> {<br /> public void InitializeDatabase(MyContext context)<br /> {<br /> context.Configuration.AutoDetectChangesEnabled = false; <br /> }<br /> }<br /><br />4) Use a basic test to write an entity a few times, and check the configuration value that we modified in the initializer:<br /><br /> public static void SimpleWrite()<br /> {<br /> for (var i = 0; i < 3; i++)<br /> {<br /> var entity = MyEntity.CreateEntity();<br /> var test = true;<br /> using (var db = new MyContext())<br /> {<br /> db.TestEntities.Add(entity);<br /> db.SaveChanges();<br /> test = db.Configuration.AutoDetectChangesEnabled;<br /> }<br /> }<br /> }<br /><br />RESULT<br /><br />- On the first call, db.Configuration.AutoDetectChangesEnabled stays false<br />- On the second and third calls, Configuration.AutoDetectChangesEnabled is true<br /><br />EXPECTED<br /><br />I would expect the configuration changes either to persist or revert for all DbContext instances, and not be different in the first one vs the consecutive ones.<br /><br />SCENARIOS<br /><br />Using DbInitializers to only modify DbContext.Configuration is NOT a use case. However, developers might modify the configuration for some other reason, perhaps to bulk insert a bunch of entities in the Initializer. This modification will persist for the first use of the DbContext in the current appdomain so the first time the DbContext is used, application might work unexpectedly<br /><br />WORKAROUND<br /><br />- In the DbInitializer, once you are done with the DbContext, you can reset the configuration<br />- You can recycle your DbContext if it's the first time in the current appdomain.
↧