使用Entity Framework Core 2.0更改或重命名列名而不会丢失数据 [英] Change or rename a column name without losing data with Entity Framework Core 2.0

查看:165
本文介绍了使用Entity Framework Core 2.0更改或重命名列名而不会丢失数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到我错误地拼写了我的列标题之一,因此我在模型中进行了更改,并创建了一个新迁移以将其更新到数据库中。在我意识到实际上似乎发生的事情是新的列替换了现有的列并擦除了所有数据之前,所有方法都运行良好。碰巧,因为这是一个教程数据库,所以没什么大不了,只需几分钟就可以将数据放回去。

I realised that I had spelt one of my column headers incorrectly so I changed it in the model and created a new migration to update it into the database. All worked perfectly until I realised that what actually appeared to happen was a new column replaced the existing column and erased all the data. As it happens, as this was a tutorial database, it was no big deal and a work of a few minutes to put the data back.

我如何/该怎么做要更新/重命名列而不丢失其中的数据?

How/what do I do to update/rename a column without losing the data in it?

不知道在我的搜索中是怎么出现的,但这是直接相关的帖子:
重命名表字段而不会丢失数据,使用自动迁移

Not sure how this didn't come up in my search but here is a directly related post: Rename table field without losing data, using automatic migrations

推荐答案

EF Core通过将模型与当前数据库进行比较来创建其迁移快照(ac#类)。然后,它使用它来创建一个您可以查看的迁移文件。如果EF Core不能始终知道您是替换此列还是创建新列。当您检查迁移文件时,请确保没有任何列删除,索引删除(与该列相关)等。您可以将所有这些替换为以下内容:

EF Core creates its migrations by comparing your models to the current database snapshot (a c# class). It then uses this to create a migration file you can review. If EF Core cannot always know if you replaced this column or created a new column. When you check your migration file, make sure there are no column drops, index drops (related to this column) etc. You can replace all these with something like this:

migrationBuilder.RenameColumn(
    name: "ColumnA",
    table: "MyTable",
    newName: "ColumnB");

这篇关于使用Entity Framework Core 2.0更改或重命名列名而不会丢失数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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