EntityFramework Modify Database Instead of Recreat

2019-08-01 05:00发布

问题:

Im working with C# MVC3 with EF 4.1. When i modify an atributte of one of my Models (IE: I add the property public bool dead {set; get;} to my Player.cs) the EF Drops and Recreate the whole Database.

I know that this happend because i have this:

Global.asax.cs

protected void Application_Start(){
    ...
    Database.SetInitializer<GameContext>(new DropCreateDatabaseIfModelChanges<GameContext>());
    ...
}

I just want to EF add the new column to my Player table, no re-create the full database, i had the same problem with Django, but i used South to solve that (an amaizing tool). Exist something similar to the EF?

I can't seed the Database with an public class GameInitializer : DropCreateDatabaseIfModelChanges<GameContext> definition and put all the values by myself, because are dinamic.

I hardly think that the only option is to add manually the columns to my table, well... i have a problem with that, when i add the MDF File to my server explorer, the project can't open the database again (even when i detached and closed the connection), its kinda strange.

Well, that's my problem! TIA.

回答1:

EF currently don't have any incremental way to build the database but there is separate project called Code First Migrations which will offer this functionality. Migrations are currently in Beta and should be part of future EF version.

So you can either use migrations or you must manually modify your database (try to close / open VS to solve your current issue).