实体框架更改键类型 [英] Entity Framework change Key Type

查看:68
本文介绍了实体框架更改键类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个具有各种值的模型,但愚蠢地使用 GUID 作为我的密钥,我目前正试图将其更改为 Int ,但这样做时出现错误。

I have created a model with various values but stupidly used a GUID for my key, I am currently attempting to change that to an Int but am getting an error when I do so.

我已经运行了enable migration命令:

I have run the enable migration command:

Enable-Migrations -Force -ContextTypeName project.Models.MyContext

这将创建我期望的迁移,但是当我运行时:

This creates the migration I would expect but when I run:

Update-Database -Force

我得到的错误是:


操作数类型冲突:uniqueidentifier与int不兼容

Operand type clash: uniqueidentifier is incompatible with int

我不在乎数据库中当前包含的数据,因为它现在只是使用SQL Server Express数据库,但是我宁愿找到一种方法来迁移它,而不必完全删除数据库,这样做的最佳方法是什么?

I don't care about the data currently contained within the database since it is just using a SQL Server Express database just now, but I would prefer to find a way to migrate this instead of just having to drop the DB altogether, what's the best way to do this?

我已经有

Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>());

Global.asax 中。

推荐答案

我希望生成的迁移正在使用AlterColumn尝试将字段类型从guid更改为int。这是不可能的,所以您需要自己修改生成的迁移:

I would expect that the generated migration is using AlterColumn to try and change the type of the field from guid to int. This is not possible, so you'll need to modify the generated migration yourself:

假设您的表是dbo.People,并且键名为Id,您可能有这个目前:

Assuming your table is dbo.People and the key is called Id, you probably have this at the moment:

DropPrimaryKey("dbo.People");
AlterColumn("dbo.People", "Id", c => c.Int(nullable: false, identity: true));
AddPrimaryKey("dbo.People", "Id");

将其更改为:

DropPrimaryKey("dbo.People");
DropColumn("dbo.People", "Id");
AddColumn("dbo.People", "Id", c => c.Int(nullable: false, identity: true));
AddPrimaryKey("dbo.People", "Id");

请注意,如果您在其他地方引用了此密钥,则该技术将不起作用呈现了所有数据,因为所有密钥都在重新生成。

Note that if you've got this key referenced elsewhere, this technique will not work if you've got any data present, as the keys are all being regenerated.

这篇关于实体框架更改键类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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