how change db initializer strategy in codefirst?

Oct 12, 2011 at 5:51 PM

Doing some prototyping and I'd quite like to be using the RecreateDatabaseIfModelChanges initializer strategy (as per

The code in that blog says:

static void Main(string[] args) 

new RecreateDatabaseIfModelChanges<ProductCatalog>());


where "ProductCatalog" is the DB context.

I imagine I need to get hold of the underlying DB context, which I imagine comes from the EntityPersistor (although of course, there could be many DB contexts so I suppose I also need to indicate which).


Oct 12, 2011 at 6:00 PM

It is easy enough to get hold of the DB Context. This is in the manual (though the search on the .chm is so un-reliable you'd be forgiven for not finding it):

The DB Context is accessible by by casting the results of the Container.Instances<T>() method as an ObjectQuery. It is not important what type you make T (as long as it is one of your domain entity types) as the resulting context is not typed. For example:

var context = ((ObjectQuery) Container.Instances()).Context

Accessing the DB context directly should be done with extreme care, and only if you know what you are doing. Invoking arbitrary functions on the context could cause errors within Naked Objects that will be extremely difficult to diagnose. One legitimate use, though, is to invoke stored procedures and functions.

However, we're not sure that invoking the functionality on the context as you indicate would work, because there isn't really an appropriate hook to ensure that it got called at the right point in the start-up sequence. However, if you can find that point (where Naked Objects figures out if there is an existing database or not and if not creates one by delegation to EF Code First) and insert a hook, please submit a patch.