acarlon
acarlon

Reputation: 17264

Entity Framework with existing database - neatest approach?

I have an existing database. To get rid of the 'context has changed since the database was created' exception that occurs with an existing database, I call the following in the Application_Start() of Global.asax.cs as is recommended in what I have read:

Database.SetInitializer<SomeEntities>( null );

The problem is that I need to add a line to Application_Start for each existing entity which has a few problems: -

  1. If I add a new entitity for an existing table, then I need to remember to call this in Application_Start(). Problem is that Application_Start is removed from the class that I am adding so I tend to forget about this which means that I keep hitting the exception.
  2. The operation on the Entity is removed from the entity code that it is acting on so it is not obvious by looking at the Entity class that the initializer is null. Which is one of the reasons that I keep forgetting - because I do not see it in my existing classes. Similarly, if I remove an entity and delete the class from my solution I need to remember to go digging in Application_Start.
  3. The startup code is cluttered with Database.SetIntializer() calls.

Ideally, I would like to call this in the constructor of the Entities class (derived from DBContext). I tried the following but it did not work:

Database.SetInitializer(false);

So, my question is, what is the best way to set the initializer inside the Entities class (i.e. class derived from DBContext) rather than in Application_Start. Perhaps a static constructor in the Entities class that calls Database.SetInitializer?

If Database.SetInitializer(false) in the constructor is the correct approach, then I will persevere with it and see where I am going wrong.

Upvotes: 0

Views: 150

Answers (1)

qujck
qujck

Reputation: 14580

The code you have put into Global.asax.cs can be put into a static constructor for the Context.

public class MyContext : DbContext
{
    static MyContext ()
    {
        Database.SetInitializer<MyContext>(null);
    }

    //...
}

References here, here and here

Upvotes: 1

Related Questions