String 如何编写第一个fluent API字符串主键?

String 如何编写第一个fluent API字符串主键?,string,entity-framework,ef-code-first,migration,primary-key,String,Entity Framework,Ef Code First,Migration,Primary Key,我尝试为成员实体创建主键,我不想使用注释,只需使用fluent API: Member{ public string MemberID {get;set;} ... } 在成员映射中 this.hasKey(t=>t.MemberID); 更新数据库时,我遇到以下错误: Identity column 'MemberID' must be of data type int, bigint, smallint, tinyint, or decimal or numeric

我尝试为成员实体创建主键,我不想使用注释,只需使用fluent API:

Member{
    public string MemberID {get;set;}
    ...
}
在成员映射中

this.hasKey(t=>t.MemberID);
更新数据库时,我遇到以下错误:

Identity column 'MemberID' must be of data type int, bigint, smallint, tinyint, or decimal or numeric with 
a scale of 0, and constrained to be nonnullable

问题不在于PK,而在于一致性。你应该吃点类似的东西

property(x => x.MemberID).HasDatabaseGeneratedOption(
    DatabaseGeneratedOption.None);

EF支持将
string
作为主键,但当需要创建
成员的实例并将其保存到数据库中时,必须使用某些值显式设置该属性。默认情况下,EF中唯一的类型是
int
。要解决您的问题,我认为您有两种选择:

  • 将数据库中的
    MemberID
    列更改为非
    Identity
    。这应该可以解决问题
  • 如果您希望EF为您进行更改,请添加以下配置:

    this.hasKey(t=>t.MemberID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
    
    使用
    addmigration
    命令创建新的迁移,然后再次尝试运行
    updatedatabase
    命令

  • 现在,如果数据库中的
    MemberID
    列不是
    Identity
    ,并且您试图将模型中的
    MemberID
    PK属性设置为
    Identity
    ,那么这也可能是问题的原因。如果是这种情况,请删除该配置并尝试再次运行
    updatedatabase
    命令

    摘自本书第44页:

    如果键字段是
    整数
    ,code First默认为
    DatabaseGeneratedOption.Identity
    。使用
    Guid
    ,您需要显式地 配置这个这些是您可以配置为的唯一类型
    Identity
    当代码第一次生成数据库时


    默认情况下,EF希望其PK列不为null。因为字符串不是值类型,所以它可以为null。另外,PK必须是某些类型的,我不认为string是其中之一。此外,EF将使PK的自动递增,这与字符串类型不匹配