【问题标题】:Using a string for an Primary Key Entity Framework Code First首先使用字符串作为主键实体框架代码
【发布时间】:2016-03-17 22:56:52
【问题描述】:

我看过这个参考:How to use String property as primary key in Entity Framework

哪些细节与我遇到的问题基本相同。 运行更新数据库命令 导致以下错误:

'标识列 'FormId' 的数据类型必须是 int、bigint、smallint、tinyint 或小数位数或小数位数为 0、未加密且限制为不可为空的数字。'

我按照上述参考说明添加了属性,并确保没有任何 Identity 属性与我尝试使用的数据库中的该列相关联,在进行这些更改后,我仍然得到相同的确切错误消息。

我真的很想知道我错过了什么。我无法从我的搜索中发现任何其他修复。非常感谢您的帮助。

public class Form
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string FormId { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string Description { get; set; }
    public string Url { get; set; }
}

public class UserForm
{
    public string UserFormId { get; set; }
    public bool IsComplete { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
    public Form Form { get; set; }

}

【问题讨论】:

  • 你能告诉我们你的代码吗?
  • @DavidG:我添加了我正在使用的特定类,这会引发问题
  • 您是否为此键定义了任何外键关系?
  • 是的,我添加了引用上面Form类的类。该类是否也需要一些关联的数据属性? UserForm 有一个外键,它将引用表单的 FormId。

标签: c# sql-server entity-framework ef-code-first


【解决方案1】:

我尝试使用字符串FormId 创建与您的模型相对应的两个表,并且一切正常。我建议您不要第一次创建表,而是将 FormId 从以前的类型(我认为是 int 类型)更改为新的 string 类型。如果是这样,在您的迁移中,您可以在您的 FormId 列中看到 AlterColumn,它尝试将 FormId 转换为新类型,但这是不可能的,因为它们不兼容。而是 AlterColumn 使用 DropColumnAddColumn 组合。看看非常相似(我假设)problem,其中试图将 PK 从int 更改为Guid 类型。

【讨论】:

  • 这似乎已经完成了,感谢您的提示和参考!
【解决方案2】:

尝试添加显式外键。

类似:

public class UserForm
{
    public string UserFormId { get; set; }
    public bool IsComplete { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
    public string FormId {get;set;}
    [ForeignKey("FormId")]
    public Form Form { get; set; }
}

【讨论】:

  • 这产生了一个新错误:类型“WisconsinTrackClubWebsite.Models.UserForm”的属性“Form”上的 ForeignKeyAttribute 无效。在依赖类型“WisconsinTrackClubWebsite.Models.UserForm”上找不到外键名称“FormId”。 Name 值应该是一个逗号分隔的外键属性名称列表。
猜你喜欢
  • 2015-09-02
  • 2011-11-07
  • 2013-01-15
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
相关资源
最近更新 更多