EF Code First 6.1 Change ID from Int to Long

﹥>﹥吖頭↗ 提交于 2021-02-07 17:24:33

问题


I'm working on an application that is using ASP.Net MVC 4, C# and Entity Framework Code First. There is one model (Table) that is growing rather large and I'm worried that the Identity column will run out of values (Int32.MaxValue) in the next year or so.

I'm looking for a way to change this identity from int to a long. In the past when I tried this, EF wouldn't let me do this unless if it dropped the table and recreated it. This is not an option since the site is already live and there is live data in this table.

Is there a way to do this? So far my web searches and Stackoverflow searches have not given me any hints on how to do this.


回答1:


Requires Code-First migrations:

1) Update your model

2) Create your migration

3) Write custom SQL in your generated migration to drop your PK and every FK that references it. This can get quite messy as you have to figure out the names. Put this above your AlterColumn.

4) Write custom SQL to re-add your PK and FKs and put it under your AlterColumn.

5) Now do the reverse in your Down script.

FYI, this isn't possible with Azure SQL. In this case you must create a new table.




回答2:


I just did this with EF 6.1.3 with SQL Server, and after changing my model and running Add-Migration, EF was able to create the correct migration on its own! Fantastic!

The best solution for those using the same setup (which I'd guess is the most common use case for EF6) is to update the EF library, change your code, create a migration as usual, and make sure it's doing what Jeff described above.



来源:https://stackoverflow.com/questions/24421081/ef-code-first-6-1-change-id-from-int-to-long

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