自动生成 ID GUID 数据类型 Entity Framework

5

我查看了这篇帖子,并尝试按照以下方式完成:

使用Entity Framework CTP5自动生成主键(GUID)

 [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
 public Guid CompanyID { set; get; }

然而,我仍然遇到了错误。
Identity column 'CompanyID' must be of data type int, bigint, smallint, tinyint, or decimal or numeric with a scale of 0, and constrained to be nonnullable.

当我在包管理器控制台上运行Update-Database命令时,就会出现这种情况。

我有一种感觉,可能是因为在CompanyID列中已经有数据了,所以它不让我这么做。 - Johnathon64
你是否将 [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] 添加到迁移的一部分?这里 lightyeare 的回答可能会有所帮助:https://dev59.com/9GAg5IYBdhLWcg3w3eJi。 - Eric Yeoman
刚刚尝试了一下,不起作用。我做了以下操作: AlterColumn("dbo.dbCompanies", "CompanyID", c => c.Guid(nullable: false, identity: true, defaultValueSql: "newsequentialid()")); - Johnathon64
你们现有的CompanyId是否已经是Guid了? 只是好奇,因为在你们之前的一个问题中,CompanyId是int类型。(http://stackoverflow.com/questions/30244351/adding-entity-to-identity-model) - Eric Yeoman
1
如果你想使用Guid,那么你需要将当前的条目也改为使用Guid,因为你不能混合使用不同的数据类型 :) 你是否检查过任何外键约束或者现有的代码是否期望一个整数?(不确定你在应用程序生命周期的哪个阶段) - Eric Yeoman
显示剩余2条评论
1个回答

3

我曾遇到相似的问题,唯一能帮助我的方法是将数据库回滚至初始空状态,删除所有迁移并创建一个新的迁移以恢复适当的GUID密钥:

  1. Update-Database -TargetMigration:0
  2. 删除所有迁移
  3. Add-Migration InitialCreate
  4. Update-Database

我同意这不是最好的解决方案,但由于我在几个小时前才开始项目,所以它对我来说是可接受的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接