3

I'm using EF 4.3.1 and I have 100+ contexts which drives 1 base context. For all contexts I want to disable Database Initialization.

Is it possible to set default behavior for Entity Framework?

Thanks in advance

2
  • Just wanted to point out that you should probably reword your question to mention that you need this behavior for multiple contexts. All the provided answers are ok for any given context. Also, you should not use tags in your question title, since it is redundant. I decided not to edit it because I feel you should rephrase it at the same time. Commented Dec 26, 2014 at 15:17
  • This question is very old but I have to ask why didn't you just comment out the initializer line in your code? Commented May 5, 2015 at 8:32

3 Answers 3

2
//Gather all the DbContexts types in the assembly
var allDbContextsTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.BaseType == (typeof(DbContext))).ToList();

foreach (Type dbContextType in allDbContextsTypes)
{
    //Get the SetInitializerMethod
    MethodInfo initializerMethod = typeof(Database).GetMethod("SetInitializer");

    //Make it generic! (Oh yeah)
    MethodInfo dbContextInitializerMethod = initializerMethod.MakeGenericMethod(dbContextType);

    //Invoke the method with null initializer
    dbContextInitializerMethod.Invoke(null, new object[]{null});
}

In the end, it gives something like : Database.SetInitializer<YourDbContext>(null); where YourDbContext is the current dbContext type in your loop

Sign up to request clarification or add additional context in comments.

Comments

2

Database.SetInitializer<TContext> is what you are after. Also passing null to this method should disable initialization.

http://msdn.microsoft.com/en-us/library/gg679461(v=vs.103).aspx

2 Comments

this is not what I looking for because I don't want to edit 100+ entities. when I run this code for base context it does not change anything and creates db.
If you had the DbInitializer code in all your derived contexts then, no, this wont work because the derived constructor runs AFTER the base constructor so all it would do is turn it off and then back on again.
2

You can change your *.config file to disable database initialization. This is done per context, but maybe it will work for your base context.

<contexts>
  <context type=" Blogging.BlogContext, MyAssembly" disableDatabaseInitialization="true" />
</contexts>

A much better explanation is given in EF 4.3 Configuration File Settings

1 Comment

This doesn't work because code override configuration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.