15

How to disable code-first feature in EF (Visual Studio 2012)

I am using Visual Studio 2012, MVC4 (Internet application template).

I want to use EF, but not with its code-first feature. I would want the application to error out, rather than create or modify my database based on my code. (i just can not live with this feeling of my database being changed behind the scenes ... i want the application to use the exact db i have created ... and if there is any thing that has to be changed, i'll do it my self)

is this possible with the new Ef (VS2012)?

i have seen many people asking this, but so far i am unable to find the answer.

M. Ali Iftikhar
  • 3,125
  • 2
  • 26
  • 36

1 Answers1

23

You can use Code First and ensure that your database never gets updated or overwritten when you change your model by setting the database initializer to null:

Database.SetInitializer<MyDbContext>(null);

It's a static method of the Database class and should be called at the beginning of your application, for example in global.asax or in a static constructor of your context class. Doing this you have to change model class and database schema manually so that they match.

You can also use the Reverse Engineer feature to create a Code First model from an existing database. It is explained here: http://msdn.microsoft.com/en-us/data/jj200620

Or if you don't want to use Code First at all and work with a model designer you can use the Database First approach, explained here: http://msdn.microsoft.com/en-us/data/jj206878

An overview about all the possible options is here: http://msdn.microsoft.com/en-us/data/ee712907.aspx

Slauma
  • 175,098
  • 59
  • 401
  • 420
  • 1
    thanks! I was going crazy looking through an existing solution trying to figure out why Code First wasn't working. And after this post I find this piece of code in the global.asax.cs -> Database.SetInitializer(null); – shake Oct 17 '14 at 02:08
  • So here's what I don't understand: In my controller, I have a private field containing the context. This field gets initialized via the parameterless constructor, which contains the above line. Next, I'm routed to a controller method, which crashes when EF tries to drop the database. How can this be? Is it related to me calling the super-constructor for the Context, with the name of my Context class as a string parameter. – Christofer Ohlsson Apr 21 '16 at 14:40