2

We are using the Code-first approach without an Edmx file, its running fine to create database the first time.

But if I am adding new data entities say new class to my database context then it is not able to add that to new table in that database.

Say for example there are two table initially in database. ex Database : DbTest

Table : Tbl1, Tbl2

Now if I add new table, say class name 'Tbl3', then it should be adding it into the existing database.

Can any one please explain to me with an example how it can be achieved via code first approach?

I have seen mentioned something like Database.SetInitializer(new ........)

What do I need to put in the blank area of the constructor above?

1 Answer 1

1

If you look in your database you will see a table called "EdmMetadata" which Entity Framework uses to determine if any changes have been made to your model since the database was created (which it has in your case).

The default behaviour is for an exception to be thrown if the model and database differ. To get different behaviour you will need to use an IDatabaseInitializer<TContext>.

Luckily, Entity Framework ships with some default implementations of this interface:

  • CreateDatabaseIfNotExists<TContext> - This will create the database if one doesn't already exist.
  • DropCreateDatabaseAlways<TContext> - This will re-create the database each time your application is run.
  • DropCreateDatabaseIfModelChanges<TContext> - This will re-create the database if a change is detected in the EdmMetadata table (usually as a result of creating new tables).

You can of course also create your own implementation of this interface by overriding the InitializeDatabase method.

an example of using one of these initialization strategies is shown below:

Database.SetInitializer(
    new DropCreateDatabaseIfModelChanges<NameOfYourDbContextClass>())

Think carefully before choosing an initialization strategy as you could end up losing data already entered into the database and this may not be what you want.

The implementations provided by Entity Framework provide a Seed method for loading your database with data so that you can preload your database with default data each time it is created.

This article provides further information.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.