Mike Bailey Mike Bailey - 9 days ago 7
C# Question

Update database schema on model change without data loss

Background: Let's say I'm using the entity framework and one of the entities mapped is given as:

class Foo
{
public int ID { get; set; }
public string Bar { get; set; }
// other useful properties
}


With the mapping:

class FooMap : EntityTypeConfiguration<Foo>
{
// bear me with, I know this is redundant right now
ToTable("Foo");
HasKey(e => e.ID);
Property(e => e.ID).HasColumnName("ID");
Property(e => e.Bar);
}


Somewhere down the road we need to change the column name of
Foo
because my boss tells me the
Foo
needs to have a more extravagant name than
ID
or else our customers will be unhappy. He tells us to rename it too "FooID":

class FooMap : EntityTypeConfiguration<Foo>
{
// bear me with, I know this is redundant right now
ToTable("Foo");
HasKey(e => e.ID);
Property(e => e.ID).HasColumnName("FooID"); // Now you map to FooID
Property(e => e.Bar);
}


As it stands, if I run this nothing will have changed. The
Foo
table will still have a column named
ID
and it'll throw an exception telling me that the column
FooID
doesn't exist.

The Question: How can I get the entity framework to recognize that I now wish to update the
Foo
table so that the column named
ID
is now named
FooID
?

More generally, how can I get the entity framework to automatically propagate changes from my code into the actual database (say at the application start up) WITHOUT destroying existing data?

I can't just "Drop and re-create" the database because, for reasons beyond the scope of this question, the database stores some other data in it that isn't created via the models mapped in my code. Dropping it would cause us to lose tables that we can't just recreate using this mechanism.

Ray Ray
Answer