Search code examples
entity-framework-4code-firstef4-code-only

Change model after database is created on EF4 code only


Hey, sorry for my bad english... Using EF4 code-only, I have created some POCO classes and my database was generated from that. All worked fine, I inserted some data on the tables but now I need to create a new property on one of my classes. If i just create it, the application give me the exception: {"The model backing the 'TestContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the RecreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data."}

I tried to create manually the field on the table, but it is still complaining... does someone know if there is a way and if so how can I manually update the database schema (i don't want to recreate it because i already have data) to match the model?


Solution

  • It should work if you make sure that your new column match exactly your new property.

    For example, if you add a property NewProp

    public class MyEntity
    {
        [Key]
        public int Id;
    
        public string PropA;
        public int PropB;
    
        public int NewProp;
    
    }
    

    then in your database table MyEntities, you would add a column NewProp of type int not null.

    What you can do to check if the column you add is correct, is to rename your database, then let Code-First recreate the database and see what's different between the original and new databases.