如何从现有数据库自动生成MigrationBuilder [英] How to auto generate the MigrationBuilder from an existent DB

查看:523
本文介绍了如何从现有数据库自动生成MigrationBuilder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个Asp.Net Core项目。该项目附带一个用于迁移的文件。该文件将生成我的数据库。但是我在数据库中有一些表,我想像示例中那样创建迁移文件。

I'm creating a Asp.Net Core project. The project came with a file for migration. This file will generate my DB. But I have some tables in a DB and I would like create the migration file like in the sample.

示例:

migrationBuilder.CreateTable(
               name: "AspNetRoles",
               columns: table => new
               {
                Id = table.Column<string>(nullable: false),
                ConcurrencyStamp = table.Column<string>(nullable: true),
                Name = table.Column<string>(maxLength: 256, nullable: true),
                NormalizedName = table.Column<string>(maxLength: 256, nullable: true)
              },
              constraints: table =>
              {
                    table.PrimaryKey("PK_AspNetRoles", x => x.Id);
              });

如果我有一个现有的表。如何创建此文件?

If I have an existent Table. How can I create this file?

推荐答案

MigrationBuilder 仅存在于EntityFramworkCore中。请注意EntityFramworkCore和EntityFramwork 6.x之间的区别。 EntityFramworkCore的文档位于此处。可以解决您问题的教程是此处

MigrationBuilder only exists in EntityFramworkCore. Be careful of the difference between EntityFramworkCore and EntityFramwork 6.x. The documentation of EntityFramworkCore is here. The tutorial that may solve your problem is here.


  1. 运行类似这样的内容:

  1. Run something like this:

Scaffold-DbContext Server =(localdb)\mssqllocaldb; Database = Blogging; Trusted_Connection = True; Microsoft.EntityFrameworkCore.SqlServer

从数据库反向工程模型。这还会为您生成模型快照和迁移(如果不能自己运行Add-Migration,则不能确定)。

to reverse engineer a model from the database. This will also generate model snapshots and migrations(not so sure, if not run Add-Migration yourself) for you.

现在,您将获得迁移文件,并且模型与数据库同步。

Now you get the migration files and your models and the database are in sync.

另外,值得一看功能比较了解EntityFramworkCore不支持的内容。到目前为止,
EntityFramworkCore没有EntityFramwork 6.x拥有的许多GUI工具。例如,您不能使用其他答案中提到的实体数据模型向导。如果您偶然使用GUI工具,则默认情况下它将生成与EntityFramwork 6.x相关的东西。因此,您必须在Visual Studio的 Package Manager控制台中使用 cmdlet 来完成这些任务。

Also, it is worth to have a look at the Feature Comparesion to get a feeling of what EntityFramworkCore does not support. Until now, EntityFramworkCore doesn't have many of the GUI tools that EntityFramwork 6.x has. For example, you cannot use Entity Data Model Wizard that is mentioned in the other answer. If you use the GUI tools by accident, it will generate EntityFramwork 6.x related stuff by default. So, you have to use cmdlet in the Package Manager Console in Visual Studio do such tasks.

这篇关于如何从现有数据库自动生成MigrationBuilder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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