在 SQL Server 2008 上设置实体框架代码优先数据库

发布于 2024-12-24 00:33:27 字数 886 浏览 1 评论 0原文

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

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

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

我尝试过:

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

但这一开始不起作用,因为它找不到 EdmMetaData 表来发现模型是否已更改。

所以我尝试添加:

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

但这不起作用,因为我已经创建了数据库,当我删除数据库时,它仍然不起作用,因为我登录的用户没有创建数据库权限。

我终于尝试了:

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

哪个有效,但我真的不想每次都删除数据库。因此,一旦它运行并添加了 EdmMetaData 表,我就用方法 1 替换了它,现在效果很好。

虽然这个方法可行,但是感觉不像我使用 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.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡笑忘祈一世凡恋 2024-12-31 00:33:27

方法 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文