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

查看:25
本文介绍了使用 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 通过将您的模型与当前数据库快照(一个 c# 类)进行比较来创建其迁移.然后它使用它来创建一个您可以查看的迁移文件.如果 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天全站免登陆