I successfully created my first Entity Framework Code first project using SQL Server CE. The database tables were created automatically and all was well.

I then changed my connection string to point to a SQL Server database I'd created and expected it to autogenerate the tables. It didn't and instead complained about the tables not existing.

After some reading I found that I needed to add an initializer to my App_Start method.

I tried:

// Method 1
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<EFContext>());

But this didn't work at first because it couldn't find an EdmMetaData table to discover if the model had changed.

So I tried adding:

// Method 2
Database.SetInitializer(new CreateDatabaseIfNotExists<EFContext>());

But this didn't work because I'd already created the database, and when I removed the database it still didn't work because the user I was logging in as didn't have create database privileges.

I finally tried:

// Method 3
Database.SetInitializer(new DropCreateDatabaseAlways<EFContext>());

Which worked, but I don't really want to drop the db every time. So once it ran and added the EdmMetaData table I replaced it with method 1 and that now works fine.

Although this method works, it doesn't feel as elegant as when I was using SQL Server CE and I've not found someone suggesting that you use this method.

So, am I missing something and is there an easier, more elegant way to do this?

share|improve this question
feedback

1 Answer

up vote 1 down vote accepted

Method 1 and 2 expects that database doesn't exist yet. They don't work if you create database manually. If you need EF to create tables in existing database you must create custom database initializer.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.