How to use String property as primary key in Entity Framework(如何在实体框架中使用字符串属性作为主键)
问题描述
我是 EF 的新手,尝试在 ETF6.0 中通过代码优先的方法完成我的第一步,现在我遇到了问题.
I'm new in EF and try to do my first steps by code first approach in ETF6.0 and now i have a problem.
我有财产
[Key]
public string FooId { get; set; }
这是我的模型主键.
但是如果我运行
PM> 更新数据库
包管理器控制台中的命令更新挂起的数据库迁移我收到以下错误:
command in package manager console to update pending migrations to the database i get the following error:
标识列FooId"的数据类型必须为 int、bigint、smallint、tinyint,或小数或刻度为 0 的数字,并限制为不可为空.
Identity column 'FooId' must be of data type int, bigint, smallint, tinyint, or decimal or numeric with a scale of 0, and constrained to be nonnullable.
如果我将模型中的 PK 更改为
If I change the PK in my model to
[Key]
public int FooId { get; set; }
一切正常.
但我需要 PK 为字符串类型,因为它在我的情况下绝对有意义.我知道有缺点,但对我来说这是必要的.
But I would need the PK to be of type string because it makes absolutely sens in my case. I know there are disadvantages but for me it is necessary.
我在这里看到了一篇较旧的帖子 如何制作字符串作为实体框架中的主键!.
I saw an older post here How to make string as primary key in entity framework!.
但这似乎没有解决我的问题,或者我只是不明白.
But it seems not to solve my problem or I just don't understand it.
真的不能在SQL数据库中使用字符串作为PK吗?
Is it really that I can't use a string as PK on a SQL database?
或者有什么办法吗?
推荐答案
这是在不启用身份自动增量的情况下创建 PK 的正确方法:
This is the proper way of creating a PK without Identity Autoincrement enabled:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string FooId { get; set; }
这篇关于如何在实体框架中使用字符串属性作为主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!