EntityFramework Core迁移时出现数据库已存在对象问题解决方案

本文涉及的产品
云数据库 RDS SQL Server,独享型 2核4GB
简介:

前言

刚开始接触EF Core时本着探索的精神去搞,搞着搞着发现出问题了,后来就一直没解决,觉得很是不爽,借着周末好好看看这块内容。

EntityFramework Core迁移出现对象在数据库中已存在

在EF Core之前对于迁移的命令有很多,当进行迁移出现对象已在数据库中存在时我们通过如何命令即可解决:

Add-Migration Initial -IgnoreChanges

但是在EF Core对于迁移现如今只存在如下两个命令:

dotnet ef migrations add <<migration_name>>
dotnet ef database update

当我们第一次进行初始化迁移时,表结构完全生成通过 dotnet ef migration add initial 来初始化表,当下次再进行迁移时因为这样或者那样无意的操作导致出现如下结果

翻译成英语则是如下的情况:

There is already an object named in the database

如下为第一次初始化的迁移文件,如下:

复制代码
    public partial class initial : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Blog",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    Code = table.Column<string>(nullable: false),
                    Count = table.Column<int>(nullable: false),
                    Name = table.Column<string>(nullable: true),
                    Url = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Blog", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "Book",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    Name = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Book", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "Category",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    Name = table.Column<string>(nullable: true),
                    ProductId = table.Column<int>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Category", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "Product",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    Code = table.Column<string>(nullable: true),
                    Name = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Product", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "Post",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    BlogId = table.Column<int>(nullable: false),
                    Content = table.Column<string>(nullable: true),
                    Title = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Post", x => x.Id);
                    table.ForeignKey(
                        name: "FK_Post_Blog_BlogId",
                        column: x => x.BlogId,
                        principalTable: "Blog",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "ProductCategory",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    CategoryId = table.Column<int>(nullable: false),
                    ProductId = table.Column<int>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_ProductCategory", x => x.Id);
                    table.ForeignKey(
                        name: "FK_ProductCategory_Category_CategoryId",
                        column: x => x.CategoryId,
                        principalTable: "Category",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                    table.ForeignKey(
                        name: "FK_ProductCategory_Product_ProductId",
                        column: x => x.ProductId,
                        principalTable: "Product",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateIndex(
                name: "IX_Post_BlogId",
                table: "Post",
                column: "BlogId");

            migrationBuilder.CreateIndex(
                name: "IX_ProductCategory_CategoryId",
                table: "ProductCategory",
                column: "CategoryId");

            migrationBuilder.CreateIndex(
                name: "IX_ProductCategory_ProductId",
                table: "ProductCategory",
                column: "ProductId");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Book");

            migrationBuilder.DropTable(
                name: "Post");

            migrationBuilder.DropTable(
                name: "ProductCategory");

            migrationBuilder.DropTable(
                name: "Blog");

            migrationBuilder.DropTable(
                name: "Category");

            migrationBuilder.DropTable(
                name: "Product");
        }
复制代码

此时为了解决上述问题前提是最初的迁移类文件还在,我们需要将Up方法里面的数据全部删除而对于Down方法里面的数据可删除可不删除

复制代码
    public partial class initial : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {}

        protected override void Down(MigrationBuilder migrationBuilder)
        {
              ........   
        }
    }    
复制代码

通过Up方法来创建表或者修改列,通过Down方法来删除表或者修改列。上面我们创建了BlogType列,此时我们在映射时将其删除同时在Blog类中删除此字段,如下:

复制代码
    public class BlogMap : EntityMappingConfiguration<Blog>
    {
        public override void Map(EntityTypeBuilder<Blog> b)
        {
            b.ToTable("Blog");
            b.HasKey(k => k.Id);

            b.Property(p => p.Count);
            b.Property(p => p.Url);
            b.Property(p => p.Name);

            b.Property(p => p.Code).IsRequired();
            //b.Property(p => p.BlogType).HasColumnType("TINYINT").IsRequired();
        }
    }
复制代码

此时我们再来进行迁移如下:

dotnet ef migrations add removeBlogType

此时将不会再报错且生成的removeBlogType迁移类文件如下:

复制代码
    public partial class removeBlogType : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: "BlogType",
                table: "Blog");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<byte>(
                name: "BlogType",
                table: "Blog",
                type: "TINYINT",
                nullable: false,
                defaultValue: (byte)0);
        }
    }
复制代码

我们需要再次确保生成的迁移类文件是否是我们需要修改的字段或者对列进行修改的方法是否正确,确保无误后,接下来再来通过 dotnet ef database update 更新到数据库中

 

如上通过意外情况导致上述错误,若是将最初迁移的整个文件夹删除了肿么办,这个时候真的没有好的办法了,我能想到的是:最好事先在建立项目时建立数据库对比文件,此时就会派上用场不用一个个类去核对表同时也利于部署时进行数据迁移。

总结

本文我们讲到了在EF Core迁移时可能出现的意外情况,若是删除了最初的迁移类文件也给出了能够想到的方案,不知看到此文的你有何高见?连续发表的EF Core文章都是在项目使用中遇到的问题,所以借此机会重新过了一遍,欢迎一起探讨。







本文转自Jeffcky博客园博客,原文链接:http://www.cnblogs.com/CreateMyself/p/7043350.html,如需转载请自行联系原作者

相关实践学习
使用SQL语句管理索引
本次实验主要介绍如何在RDS-SQLServer数据库中,使用SQL语句管理索引。
SQL Server on Linux入门教程
SQL Server数据库一直只提供Windows下的版本。2016年微软宣布推出可运行在Linux系统下的SQL Server数据库,该版本目前还是早期预览版本。本课程主要介绍SQLServer On Linux的基本知识。 相关的阿里云产品:云数据库RDS&nbsp;SQL Server版 RDS SQL Server不仅拥有高可用架构和任意时间点的数据恢复功能,强力支撑各种企业应用,同时也包含了微软的License费用,减少额外支出。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/sqlserver
目录
相关文章
|
2月前
|
监控 关系型数据库 数据库
OceanBase数据库常见问题之文件存在但是数据库提示文件不存在如何解决
OceanBase 是一款由阿里巴巴集团研发的企业级分布式关系型数据库,它具有高可用、高性能、可水平扩展等特点。以下是OceanBase 数据库使用过程中可能遇到的一些常见问题及其解答的汇总,以帮助用户更好地理解和使用这款数据库产品。
|
18天前
|
关系型数据库 Apache 流计算
手把手教你实现 OceanBase 数据到阿里云数据库 SelectDB 内核版 Apache Doris 的便捷迁移|实用指南
本文介绍了如何将数据从 OceanBase 迁移到阿里云数据库 SelectDB 内核版 Apache Doris。提供 3 种数据同步方法 1. 使用 DataX,下载 DataX 并编写配置文件,通过 OceanBaseReader 和 DorisWriter 进行数据迁移。 2. 利用 Apache Doris 的 Catalog功 能,将 OceanBase 表映射到 Doris 并插入数据。 3. 通过Flink CDC,设置 OceanBase 环境,配置 Flink 连接器,实现实时数据同步。
手把手教你实现 OceanBase 数据到阿里云数据库 SelectDB 内核版 Apache Doris 的便捷迁移|实用指南
|
2天前
|
存储 Oracle 关系型数据库
oracle 数据库 迁移 mysql数据库
将 Oracle 数据库迁移到 MySQL 是一项复杂的任务,因为这两种数据库管理系统具有不同的架构、语法和功能。
12 0
|
9天前
|
存储 运维 Kubernetes
多态关联在数据库设计中的应用和解决方案
多态关联在数据库设计中的应用和解决方案
16 0
|
10天前
|
SQL 关系型数据库 MySQL
数据库的迁移
数据库的迁移
|
11天前
|
分布式计算 DataWorks 安全
DataWorks产品使用合集之在DataWorks中,“项目空间”、“数据库”和“引擎实例”之间存在怎样的关系
DataWorks作为一站式的数据开发与治理平台,提供了从数据采集、清洗、开发、调度、服务化、质量监控到安全管理的全套解决方案,帮助企业构建高效、规范、安全的大数据处理体系。以下是对DataWorks产品使用合集的概述,涵盖数据处理的各个环节。
26 0
|
12天前
|
关系型数据库 MySQL 测试技术
【专栏】PostgreSQL数据库向MySQL迁移的过程、挑战及策略
【4月更文挑战第29天】本文探讨了PostgreSQL数据库向MySQL迁移的过程、挑战及策略。迁移步骤包括评估规划、数据导出与转换、创建MySQL数据库、数据导入。挑战包括数据类型不匹配、函数和语法差异、数据完整性和性能问题。应对策略涉及数据类型映射、代码调整、数据校验和性能优化。迁移后需进行数据验证、性能测试和业务验证,确保顺利过渡。在数字化时代,掌握数据库迁移技能对技术人员至关重要。
|
22天前
|
存储 Oracle 关系型数据库
Oracle的模式与模式对象:数据库的“城市规划师”
【4月更文挑战第19天】在Oracle数据库中,模式是用户对象的集合,相当于数据库的城市规划,包含表、视图、索引等模式对象。模式对象是数据存储结构,如表用于存储数据,视图提供不同查看角度,索引加速数据定位。良好的模式与模式对象设计关乎数据效率、安全和稳定性。规划时需考虑业务需求、性能、安全和可扩展性,以构建高效数据库环境,支持企业业务发展。
|
25天前
|
SQL 自然语言处理 数据库连接
Django ORM的魔力:简化数据库操作与迁移
【4月更文挑战第15天】Django ORM是Django框架的关键部分,提供了一种高级的面向对象方式与数据库交互,简化了手动SQL操作。通过定义Python数据模型,开发者能轻松创建数据库表结构,使用ORM执行查询、添加、修改和删除数据。Django ORM还自动化处理数据库连接、事务和数据类型转换。当模型变化时,Django的迁移工具帮助管理数据库结构的更新。通过这种方式,Django ORM促进了高效、专注于业务逻辑的Web开发。
|
1月前
|
存储 关系型数据库 MySQL
【mybatis-plus】Springboot+AOP+自定义注解实现多数据源操作(数据源信息存在数据库)
【mybatis-plus】Springboot+AOP+自定义注解实现多数据源操作(数据源信息存在数据库)