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

简介: 前言 刚开始接触EF Core时本着探索的精神去搞,搞着搞着发现出问题了,后来就一直没解决,觉得很是不爽,借着周末好好看看这块内容。 EntityFramework Core迁移出现对象在数据库中已存在 在EF Core之前对于迁移的命令有很多,当进行迁移出现对象已在数据库中存在时我们通过如何...

前言

刚开始接触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文章都是在项目使用中遇到的问题,所以借此机会重新过了一遍,欢迎一起探讨。

目录
相关文章
|
机器学习/深度学习 人工智能 边缘计算
人工智能语音转文字(Automatic Speech Recognition, ASR)
人工智能语音转文字(Automatic Speech Recognition, ASR)
1193 1
|
人工智能 Cloud Native 文件存储
阿里云容器服务ACK云原生AI套件测评
随着人工智能(AI)技术的快速发展,越来越多的企业开始在其业务中引入AI能力,以提高运营效率、优化用户体验,以及创造新的商业价值。像我们这种小型企业也不例外,希望通过集成先进的AI技术来提升业务运营的智能化水平。在这样的背景下,阿里云容器服务ACK推出了云原生AI套件,它能够帮助企业在Kubernetes容器平台上快速构建和运行AI应用,实现全栈优化。本次通过一次实验体验,简单对云原生AI套件进行测评。
97574 58
|
10月前
|
Android开发 内存技术
fastboot工具的常见命令及其用途
`fastboot boot <文件名>.img`:不将其flash到设备上,而是直接从给定的img文件启动。这是测试新的或修改后的boot镜像而不实际安装的好方法。
4949 18
|
人工智能 搜索推荐 物联网
Android系统版本演进与未来展望####
本文深入探讨了Android操作系统从诞生至今的发展历程,详细阐述了其关键版本迭代带来的创新特性、用户体验提升及对全球移动生态系统的影响。通过对Android历史版本的回顾与分析,本文旨在揭示其成功背后的驱动力,并展望未来Android可能的发展趋势与面临的挑战,为读者呈现一个既全面又具深度的技术视角。 ####
|
存储 缓存 Android开发
Android RecyclerView 缓存机制深度解析与面试题
本文首发于公众号“AntDream”,详细解析了 `RecyclerView` 的缓存机制,包括多级缓存的原理与流程,并提供了常见面试题及答案。通过本文,你将深入了解 `RecyclerView` 的高性能秘诀,提升列表和网格的开发技能。
458 8
|
SQL 数据库 流计算
Flink CDC数据读取问题之一致性如何解决
Flink CDC 使用Change Data Capture (CDC)技术从数据库捕获变更事件,并利用Flink的流处理能力确保数据读取一致性。相较于传统工具,它具备全增量一体化数据集成能力,满足实时性需求。在实践中解决了高效数据同步、稳定同步大量表数据等问题。应用场景包括实时数据同步、实时数据集成等。快速上手需学习基本概念与实践操作。未来发展方向包括提升效率与稳定性,并依据用户需求持续优化。
549 1
|
Java 开发者 Spring
springboot DDD的概念以及实战
【5月更文挑战第15天】领域驱动设计(Domain-Driven Design,简称DDD)是一种软件设计方法论,它强调基于业务领域的复杂性来构建软件
1524 2
|
JavaScript 前端开发 API
Vue.js 深度解析:nextTick 原理与应用
Vue.js 深度解析:nextTick 原理与应用
|
前端开发 JavaScript
vue或react中修改组件样式的方法
vue或react中修改组件样式的方法
1347 0