1

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?

1 Answer 1

1

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.

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.