Setting up a Entity Framework Code First Database on SQL Server 2008

两盒软妹~` 提交于 2019-12-21 23:12:02

问题


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:


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.



来源:https://stackoverflow.com/questions/8687167/setting-up-a-entity-framework-code-first-database-on-sql-server-2008

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!