asp.net-mvc 如何为实体框架重新创建数据库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20304058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:21:37  来源:igfitidea点击:

How to re-create database for Entity Framework?

asp.net-mvcentity-frameworkazureazure-sql-database

提问by Toby Sharp

I have got into a bad state with my ASP.Net MVC 5 project, using Code-First Entity Framework. I don't care about losing data, I just want to be able to start fresh, recreate the database and start using Code-First migrations.

我的 ASP.Net MVC 5 项目使用代码优先实体框架时状态不佳。我不在乎丢失数据,我只想能够重新开始,重新创建数据库并开始使用代码优先迁移。

Currently I am in a state where every attempt to Update-Database results in an exception being thrown or getting an error message. Also the website can't access the database correctly. How can I wipe all migrations, re-create the database and start from scratch without having to create a new project? In other words, I want to keep my code but drop the database.

目前我处于每次尝试更新数据库都会导致抛出异常或收到错误消息的状态。该网站也无法正确访问数据库。如何擦除所有迁移,重新创建数据库并从头开始而不必创建新项目?换句话说,我想保留我的代码但删除数据库。

Later I will also want to get the deployment database (SQL Server on Azure) in sync. Again, I don't mind dropping all the data - I just want to get it working.

稍后我还希望同步部署数据库(Azure 上的 SQL Server)。同样,我不介意删除所有数据 - 我只是想让它工作。

Please provide any how-to steps to get back to a clean state. Much appreciated.

请提供任何操作步骤以恢复到干净状态。非常感激。

回答by Lin

Follow below steps:

请按照以下步骤操作:

1) First go to Server Explorer in Visual Studio, check if the ".mdf" Data Connections for this project are connected, if so, right click and delete.

1)首先进入Visual Studio中的Server Explorer,检查这个项目的“.mdf”Data Connections是否已连接,如果是,右击删除。

2 )Go to Solution Explorer, click show All Files icon.

2 ) 转到解决方案资源管理器,单击显示所有文件图标。

3) Go to App_Data, right click and delete all ".mdf" files for this project.

3)转到App_Data,右键单击并删除此项目的所有“.mdf”文件。

4) Delete Migrations folder by right click and delete.

4)通过右键单击并删除来删除Migrations文件夹。

5) Go to SQL Server Management Studio, make sure the DB for this project is not there, otherwise delete it.

5) 进入 SQL Server Management Studio,确保该项目的 DB 不存在,否则将其删除。

6) Go to Package Manager Console in Visual Studio and type:

6) 转到 Visual Studio 中的包管理器控制台并键入:

  1. Enable-Migrations -Force
  2. Add-Migration init
  3. Update-Database
  1. Enable-Migrations -Force
  2. Add-Migration init
  3. Update-Database

7) Run your application

7) 运行您的应用程序

Note: In step 6 part 3, if you get an error "Cannot attach the file...", it is possibly because you didn't delete the database files completely in SQL Server.

注意:在第 6 步第 3 部分中,如果出现错误“无法附加文件...”,可能是因为您没有完全删除 SQL Server 中的数据库文件。

回答by Steve Coleman

I would like to add that Lin's answer is correct.

我想补充一点,林的回答是正确的。

If you improperly delete the MDF you will have to fix it. To fix the screwed up connections in the project to the MDF. Short answer; recreate and delete it properly.

如果您不正确地删除了 MDF,您将不得不修复它。将项目中拧紧的连接固定到 MDF。简短的回答;重新创建并正确删除它。

  1. Create a new MDF and name it the same as the old MDF, put it in the same folder location. You can create a new project and create a new mdf. The mdf does not have to match your old tables, because were going to delete it. So create or copy an old one to the correct folder.
  2. Open it in server explorer [double click the mdf from solution explorer]
  3. Delete it in server explorer
  4. Delete it from solution explorer
  5. run update-database -force[Use force if necessary]
  1. 创建一个新的 MDF 并将其命名为与旧 MDF 相同的名称,并将其放在相同的文件夹位置。您可以创建一个新项目并创建一个新的 mdf。mdf 不必与您的旧表匹配,因为要删除它。所以创建或复制一个旧的到正确的文件夹。
  2. 在服务器资源管理器中打开它 [双击解决方案资源管理器中的 mdf]
  3. 在服务器资源管理器中删除它
  4. 从解决方案资源管理器中删除它
  5. 运行update-database -force[必要时使用强制]

Done, enjoy your new db

完成,享受你的新数据库

UPDATE11/12/14 - I use this all the time when I make a breaking db change. I found this is a great way to roll back your migrations to the original db:

2014 年 12 月 11 日更新- 当我进行破坏性数据库更改时,我一直使用它。我发现这是将迁移回滚到原始数据库的好方法:

  • Puts the db back to original
  • Run the normal migration to put it back to current

    1. Update-Database -TargetMigration:0 -force[This will destroy all tables and all data.]
    2. Update-Database -force[use force if necessary]
  • 将数据库放回原来的
  • 运行正常迁移以将其恢复为当前状态

    1. Update-Database -TargetMigration:0 -force[这将破坏所有表格和所有数据。]
    2. Update-Database -force[必要时使用武力]

回答by Donal

This worked for me:

这对我有用:

  1. Delete database from SQL Server Object Explorer in Visual Studio. Right-click and select delete.
  2. Delete mdf and ldf files from file system - if they are still there.
  3. Rebuild Solution.
  4. Start Application - database will be re-created.
  1. 从 Visual Studio 中的 SQL Server 对象资源管理器中删除数据库。右键单击并选择删除。
  2. 从文件系统中删除 mdf 和 ldf 文件 - 如果它们仍然存在。
  3. 重建解决方案。
  4. 启动应用程序 - 将重新创建数据库。

回答by System.Exception

While this question is premised by not caring about the data, sometimes maintenance of the data is essential.

虽然这个问题的前提是不关心数据,但有时维护数据是必不可少的。

If so, I wrote a list of steps on how to recover from Entity Framework nightmare when the database already has tables with the same name here: How to recover from Entity Framework nightmare - database already has tables with the same name

如果是这样,我写了一份关于如何在数据库已经有同名表的情况下从实体框架噩梦中恢复的步骤列表:如何从实体框架噩梦中恢复 - 数据库已经有同名表

Apparently... a moderator saw fit to delete my post so I'll paste it here:

显然……版主认为适合删除我的帖子,所以我将其粘贴在这里:

How to recover from Entity Framework nightmare - database already has tables with the same name

如何从实体框架的噩梦中恢复 - 数据库已经有同名的表

Description: If you're like us when your team is new to EF, you'll end up in a state where you either can't create a new local database or you can't apply updates to your production database. You want to get back to a clean EF environment and then stick to basics, but you can't. If you get it working for production, you can't create a local db, and if you get it working for local, your production server gets out of sync. And finally, you don't want to delete any production server data.

描述:如果您的团队刚接触 EF 时像我们一样,您最终将处于无法创建新的本地数据库或无法将更新应用到生产数据库的状态。您想回到一个干净的 EF 环境,然后坚持基础知识,但您不能。如果你让它在生产环境中工作,你就不能创建本地数据库,如果你让它在本地工作,你的生产服务器就会不同步。最后,您不想删除任何生产服务器数据。

Symptom: Can't run Update-Databasebecause it's trying to run the creation script and the database already has tables with the same name.

症状:无法运行Update-Database,因为它正在尝试运行创建脚本并且数据库已经有同名的表。

Error Message: System.Data.SqlClient.SqlException (0x80131904): There is already an object named '' in the database.

错误消息:System.Data.SqlClient.SqlException (0x80131904):数据库中已经有一个名为 '' 的对象。

Problem Background: EF understands where the current database is at compared to where the code is at based on a table in the database called dbo.__MigrationHistory. When it looks at the Migration Scripts, it tries to reconsile where it was last at with the scripts. If it can't, it just tries to apply them in order. This means, it goes back to the initial creation script and if you look at the very first part in the UP command, it'll be the CreeateTable for the table that the error was occurring on.

问题背景:EF 根据数据库中名为 dbo.__MigrationHistory 的表了解当前数据库所在位置与代码所在位置的比较。当它查看迁移脚本时,它会尝试使用脚本来协调它上次到达的位置。如果不能,它只会尝试按顺序应用它们。这意味着,它返回到初始创建脚本,如果您查看 UP 命令的第一部分,它将是发生错误的表的 CreeateTable。

To understand this in more detail, I'd recommend watching both videos referenced here: https://msdn.microsoft.com/en-us/library/dn481501(v=vs.113).aspx

要更详细地了解这一点,我建议您观看此处引用的两个视频:https: //msdn.microsoft.com/en-us/library/dn481501(v=vs.113).aspx

Solution: What we need to do is to trick EF into thinking that the current database is up to date while not applying these CreateTable commands. At the same time, we still want those commands to exist so we can create new local databases.

解决方案:我们需要做的是让 EF 认为当前数据库是最新的,而不应用这些 CreateTable 命令。同时,我们仍然希望这些命令存在,以便我们可以创建新的本地数据库。

Step 1: Production DB cleanFirst, make a backup of your production db. In SSMS, Right-Click on the database, Select "Tasks > Export Data-tier application..." and follow the prompts. Open your production database and delete/drop the dbo.__MigrationHistory table.

第 1 步:清理生产数据库首先,备份您的生产数据库。在 SSMS 中,右键单击数据库,选择“任务 > 导出数据层应用程序...”并按照提示操作。打开您的生产数据库并删除/删除 dbo.__MigrationHistory 表。

Step 2: Local environment cleanOpen your migrations folder and delete it. I'm assuming you can get this all back from git if necessary.

第 2 步:本地环境清理打开您的迁移文件夹并将其删除。我假设您可以在必要时从 git 中取回这一切。

Step 3: Recreate InitialIn the Package Manager, run "Enable-Migrations" (EF will prompt you to use -ContextTypeName if you have multiple contexts). Run "Add-Migration Initial -verbose". This will Create the initial script to create the database from scratch based on the current code. If you had any seed operations in the previous Configuration.cs, then copy that across.

第 3 步:重新创建初始在包管理器中,运行“Enable-Migrations”(如果您有多个上下文,EF 将提示您使用 -ContextTypeName)。运行“Add-Migration Initial -verbose”。这将创建初始脚本以根据当前代码从头开始创建数据库。如果您在之前的 Configuration.cs 中有任何种子操作,请复制该操作。

Step 4: Trick EFAt this point, if we ran Update-Database, we'd be getting the original error. So, we need to trick EF into thinking that it's up to date, without running these commands. So, go into the Up method in the Initial migration you just created and comment it all out.

第 4 步:欺骗 EF此时,如果我们运行Update-Database,我们将得到原始错误。因此,我们需要让 EF 认为它是最新的,而无需运行这些命令。因此,进入您刚刚创建的初始迁移中的 Up 方法并将其全部注释掉。

Step 5: Update-DatabaseWith no code to execute on the Up process, EF will create the dbo.__MigrationHistory table with the correct entry to say that it ran this script correctly. Go and check it out if you like. Now, uncomment that code and save. You can run Update-Databaseagain if you want to check that EF thinks its up to date. It won't run the Up step with all of the CreateTable commands because it thinks it's already done this.

第 5 步:更新数据库在 Up 过程中没有要执行的代码,EF 将创建带有正确条目的 dbo.__MigrationHistory 表,说明它正确运行了此脚本。喜欢的话就去看看吧。现在,取消注释该代码并保存。如果您想检查 EF 是否认为它是最新的,您可以再次运行Update-Database。它不会使用所有 CreateTable 命令运行 Up 步骤,因为它认为它已经完成了。

Step 6: Confirm EF is ACTUALLY up to dateIf you had code that hadn't yet had migrations applied to it, this is what I did...

第 6 步:确认 EF 实际是最新的如果您的代码尚未应用迁移,这就是我所做的...

Run "Add-Migration MissingMigrations" This will create practically an empty script. Because the code was there already, there was actually the correct commands to create these tables in the initial migration script, so I just cut the CreateTable and equivalent drop commands into the Up and Down methods.

运行“Add-Migration MissingMigrations”这实际上将创建一个空脚本。因为代码已经存在,所以在初始迁移脚本中实际上有创建这些表的正确命令,所以我只是将 CreateTable 和等效的 drop 命令剪切到 Up 和 Down 方法中。

Now, run Update-Databaseagain and watch it execute your new migration script, creating the appropriate tables in the database.

现在,再次运行Update-Database并观察它执行您的新迁移脚本,在数据库中创建适当的表。

Step 7: Re-confirm and commit.Build, test, run. Ensure that everything is running then commit the changes.

第七步:再次确认并提交。构建、测试、运行。确保一切都在运行,然后提交更改。

Step 8: Let the rest of your team know how to proceed.When the next person updates, EF won't know what hit it given that the scripts it had run before don't exist. But, assuming that local databases can be blown away and re-created, this is all good. They will need to drop their local database and add create it from EF again. If they had local changes and pending migrations, I'd recommend they create their DB again on master, switch to their feature branch and re-create those migration scripts from scratch.

第 8 步:让团队的其他成员知道如何继续。当下一个人更新时,EF 将不知道是什么击中了它,因为它之前运行的脚本不存在。但是,假设本地数据库可以被吹走并重新创建,这一切都很好。他们将需要删除他们的本地数据库并再次从 EF 添加创建它。如果他们有本地更改和挂起的迁移,我建议他们在 master 上再次创建他们的数据库,切换到他们的功能分支并从头开始重新创建这些迁移脚本。

回答by Dudi

Just want to add to the excellent answer of @Lin:

只想补充@Lin的优秀答案:

5) B. If you don't have SQL Management Studio, go to "SQL Server Object Explorer". If you cannot see your project db in the localdb "SQL Server Object Explorer", then click on "Add SQL server" button to add it to the list manually. Then you can delete the db from the list.

5) B. 如果您没有 SQL Management Studio,请转到“SQL Server 对象资源管理器”。如果在 localdb“SQL Server 对象资源管理器”中看不到您的项目数据库,请单击“添加 SQL 服务器”按钮将其手动添加到列表中。然后你可以从列表中删除数据库。

回答by edencorbin

A possible very simple fix that worked for me. After deleting any database references and connections you find in server/serverobject explorer, right click the App_Data folder (didn't show any objects within the application for me) and select open. Once open put all the database/etc. files in a backup folder or if you have the guts just delete them. Run your application and it should recreate everything from scratch.

一个对我有用的可能非常简单的修复。删除您在服务器/服务器对象资源管理器中找到的任何数据库引用和连接后,右键单击 App_Data 文件夹(没有为我显示应用程序中的任何对象)并选择打开。一旦打开,就把所有的数据库/等。备份文件夹中的文件,或者如果您有胆量删除它们。运行您的应用程序,它应该从头开始重新创建所有内容。

回答by Mbuso Mkhize

My solution is best suited for:
- deleted your mdf file
- want to re-create your db.

我的解决方案最适合于
- 删除了您的 mdf 文件
- 想要重新创建您的数据库。

In order to recreate your databaseyou need add the connection using Visual Studio.

为了重新创建您的数据库,您需要使用 Visual Studio 添加连接。

Step 1: Go to Server Explorer add new connection( or look for a add db icon).

步骤 1:转到服务器资源管理器添加新连接(或查找添加数据库图标)。

Step 2: Change Datasourceto Microsoft SQL Server Database File.

第 2 步:将数据源更改为Microsoft SQL Server 数据库文件

Step 3: add any database name you desire in the Database file namefield.(preferably the same name you have in the web.config AttachDbFilenameattribute)

第 3 步:在数据库文件名字段中添加您想要的任何数据库名称。(最好与您在 web.config AttachDbFilename属性中的名称相同)

Step 4: click browse and navigate to where you will like it to be located.

第 4 步:单击浏览并导航到您希望它所在的位置。

Step 5: in the package manager console run command update-database

第 5 步:在包管理器控制台中运行命令update-database