Change or rename a column name without losing data with Entity Framework Core 2.0

穿精又带淫゛_ 提交于 2019-12-10 17:06:12

问题


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


回答1:


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");


来源:https://stackoverflow.com/questions/50178413/change-or-rename-a-column-name-without-losing-data-with-entity-framework-core-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!