EF代码如何先流利API字符串主键?
How to EF code first fluent API string primary key?
我试过给Member实体做主键,不想用注解,直接用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
作为 PK,但是当您需要创建 Member
的实例并将其保存到数据库中时,您必须明确设置 属性 具有一些值。 EF 中唯一默认为 identity 的类型是 int
。要解决您的问题,我认为您有两种选择:
- 将数据库中的
MemberID
列更改为不是 Identity
。那应该可以解决问题。
如果您希望 EF 为您进行更改,请添加此配置:
this.hasKey(t=>t.MemberID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
使用 Add-Migration
命令创建新的迁移并再次尝试 运行 Update-Database
命令。
现在,如果您的数据库中的 MemberID
列不是 Identity
,并且您正在尝试将 MemberID
PK 属性 设置为 Identity
在您的模型中,这也可能是您问题的原因。如果是这种情况,请删除该配置并再次尝试 运行 Update-Database
命令。
来自 Programming Entity Framework Code First 书,第 44 页:
In the case where the Key field is an Integer
, Code First defaults to
DatabaseGeneratedOption.Identity
. With a Guid
, you need to explicitly
configure this. These are the only types that you can configure to be
Identity
when Code First is generating the database.
我试过给Member实体做主键,不想用注解,直接用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
作为 PK,但是当您需要创建 Member
的实例并将其保存到数据库中时,您必须明确设置 属性 具有一些值。 EF 中唯一默认为 identity 的类型是 int
。要解决您的问题,我认为您有两种选择:
- 将数据库中的
MemberID
列更改为不是Identity
。那应该可以解决问题。 如果您希望 EF 为您进行更改,请添加此配置:
this.hasKey(t=>t.MemberID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
使用
Add-Migration
命令创建新的迁移并再次尝试 运行Update-Database
命令。
现在,如果您的数据库中的 MemberID
列不是 Identity
,并且您正在尝试将 MemberID
PK 属性 设置为 Identity
在您的模型中,这也可能是您问题的原因。如果是这种情况,请删除该配置并再次尝试 运行 Update-Database
命令。
来自 Programming Entity Framework Code First 书,第 44 页:
In the case where the Key field is an
Integer
, Code First defaults toDatabaseGeneratedOption.Identity
. With aGuid
, you need to explicitly configure this. These are the only types that you can configure to beIdentity
when Code First is generating the database.