在SQL Server 2008上设置实体框架代码第一个数据库 [英] Setting up a Entity Framework Code First Database on SQL Server 2008

查看:149
本文介绍了在SQL Server 2008上设置实体框架代码第一个数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用SQL Server CE成功创建了我的第一个实体框架代码第一个项目。数据库表是自动创建的,一切都很好。

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

然后我更改了我的连接字符串,指向我创建的SQL Server数据库,并预期它会自动生成表。没有,而是抱怨表不存在。

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.

经过阅读后,我发现我需要添加一个初始化程序到我的 App_Start 方法。

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

我试过:

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

但是最初没有工作,因为它找不到EdmMetaData表来发现是否模型已经改变。

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

所以我尝试添加:

// 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.

我终于尝试了:

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

哪个工作,但我不想每次都丢弃db。所以一旦运行并添加了EdmMetaData表,我用方法1替换它,现在工作正常。

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.

尽管这种方法有效,但它并不像以前那样优雅我使用的是SQL Server CE,我还没有发现有人建议您使用这种方法。

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和2希望数据库不存在。如果您手动创建数据库,它们不起作用。如果您需要EF在现有数据库中创建表,则必须创建自定义数据库初始化程序

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.

这篇关于在SQL Server 2008上设置实体框架代码第一个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆