3

Entity framework has three initializers I'm aware of - CreateDatabaseIfNotExists, DropCreateDatabaseWhenModelChanges and DropCreateDatabaseAlways. When model changes, they either drop all data, or die.

I want an initializer that would extent the existing database to match the model. If a table is missing, create it, if some columns changed, rename them and make new copies, etc. Naturally, there is a lot to be considered, in particular when it comes to references, but I'm sure something more sensible than dropping the data can be done.

Does such initializer exist? If not, how could I write one?

To clarify, I want to read the changes detected by EF, and if, say, a column changed from int to double, I want to make the change while preserving my data. Complex interactions between reference columns don't need to be considered.

Karolis Juodelė
  • 3,708
  • 1
  • 19
  • 32
  • There is no way for an automatized process to tell whether a column is new or renamed. This always requires some human intervention (i.e. hard-coded renames in the Up method). – Gert Arnold Feb 24 '14 at 08:09
  • @GertArnold, for simple columns, addition and renaming might as well be handled the same. I agree that there are plenty of things which cannot be decided, but if column `Foo varchar(50)` changed to `Foo verchar(60)` there exists a sensible automatic migration and I want it. – Karolis Juodelė Feb 24 '14 at 10:07

2 Answers2

3

You can find couple of database initializers similar what you want to do in this thread

Great source of information is of course the sources of EF :

There are a lot of custom database initializers in test projects. Plus there is a bonus: DbContext for SQL metadata in file $\test\EntityFramework\FunctionalTests.Transitional\Migrations\TestHelpers\InfoContext.cs: you can query the sql metadata using linq.

Community
  • 1
  • 1
Ben
  • 2,454
  • 26
  • 32
2

There is no function like that available for the database however I would look into Database Migration. I don't find it particularly easy but this is definitely what you are looking for. Do some research into that and it should be obvious quite quickly :)

http://msdn.microsoft.com/en-gb/data/jj554735.aspx,

http://msdn.microsoft.com/en-gb/data/jj591621.aspx

Heberda
  • 830
  • 7
  • 29