[英]How to change database after altering model in MVC?
I'm new to ASP.NET and I'm working on this project that uses MVC. 我是ASP.NET的新手,正在从事使用MVC的项目。 It's a simple website development project, and it uses SQL Server CE (
.sdf
) as the database. 这是一个简单的网站开发项目,它使用SQL Server CE(
.sdf
)作为数据库。
I would like to change a couple of the underlying models, but that causes errors in the database. 我想更改几个基础模型,但这会导致数据库错误。
I understand that I would need to change the database, and I know it's possible to create models automatically from the database. 我知道我需要更改数据库,并且我知道可以从数据库自动创建模型。
I'm wondering if there is any way to create a database from the models. 我想知道是否有任何方法可以从模型创建数据库。 ie I don't mind losing all the data, but is there a way for me to change the models and then create a database that supports the existing models.
即我不介意丢失所有数据,但是有办法让我更改模型,然后创建一个支持现有模型的数据库。
I hope that makes sense 我希望这是有道理的
Yes it possible to Here is how you can do it. 是的,有可能做到这一点。 There are two approaches to accomplish this task.
有两种方法可以完成此任务。
Method-1. 方法1。 (Via Package Manager Console)
(通过软件包管理器控制台)
This approach for the Code First. 这种方法适用于Code First。
Open your project and go to Package Manager Console as follows 打开项目,然后转到Package Manager Console,如下所示
Tools--> Nuget Package Manager--> Package Manager Console
First Enable Migrations in your project.Type following in console. 首先在项目中启用迁移。在控制台中键入以下内容。
enable-migrations -contexttypename yourContextName
This command will add a Migrations folder in your project inside this folder you will see Configuration.cs inside this file you will see a seed method 此命令将在您的项目中的此文件夹中添加一个Migrations文件夹,您将在此文件中看到Configuration.cs,您将看到一个种子方法
protected override void Seed(YourContext context)
you can use this method to seed your database. 您可以使用此方法来播种数据库。
Now run following command in your package manager console 现在在包管理器控制台中运行以下命令
add-migration anyNameOfInitialMigrations
Finally To update the database simply run following command. 最后,要更新数据库,只需运行以下命令。
update-database
Method-2. 方法2。 Best approach for Model First.
模型优先的最佳方法。 Open your .edmx file.
打开您的.edmx文件。
Right Click--> on the model and then select "Generate Database From Model"
Make Sure you have proper connection strings in your web.config. 确保您的web.config中具有正确的连接字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.