I am using Entity Framework code-first. I have a table the will not exceed 100 rows and I would like to use the datatype byte
(tinyint
in SQL Server) as the primary key.
我正在使用实体框架代码优先。我有一个表不会超过100行,我想使用数据类型字节(SQL Server中的tinyint)作为主键。
This is what I have so far:
这是我到目前为止:
[Key]
public byte Id { get; set; }
The issue is when Entity Framework creates the database, it is not setting the identity specification property that allows the rows to auto increment on insert.
问题是当Entity Framework创建数据库时,它没有设置允许行在插入时自动递增的标识规范属性。
If I change the datatype to Int16
(smallint
in SQL Server) everything works perfectly.
如果我将数据类型更改为Int16(SQL Server中的smallint),一切都很完美。
Is there a way to tell Entity Framework to set the auto increment property or can a byte not be used as the primary key with Entity Framework code-first?
有没有办法告诉实体框架设置自动增量属性,还是一个字节不能用作实体框架代码优先的主键?
1 个解决方案
#1
13
The byte
type is supported as key and as an identity column. It is just not the default to mark the byte
primary key as identity. But you can overwrite this default:
支持字节类型作为键和标识列。将字节主键标记为标识不是默认设置。但您可以覆盖此默认值:
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public byte Id { get; set; }
Setting the Identity
option explicitly is not necessary for an int
, a long
and a short
(and perhaps more types?), but it is for a byte
(= tinyint
in SQL Server). I figured it out by testing but couldn't find it officially documented anywhere.
明确地设置Identity选项对于int,long和short(以及可能更多类型?)不是必需的,但它是一个字节(在SQL Server中为tinyint)。我通过测试得出结论,但无法在任何地方找到正式记录。
#1
13
The byte
type is supported as key and as an identity column. It is just not the default to mark the byte
primary key as identity. But you can overwrite this default:
支持字节类型作为键和标识列。将字节主键标记为标识不是默认设置。但您可以覆盖此默认值:
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public byte Id { get; set; }
Setting the Identity
option explicitly is not necessary for an int
, a long
and a short
(and perhaps more types?), but it is for a byte
(= tinyint
in SQL Server). I figured it out by testing but couldn't find it officially documented anywhere.
明确地设置Identity选项对于int,long和short(以及可能更多类型?)不是必需的,但它是一个字节(在SQL Server中为tinyint)。我通过测试得出结论,但无法在任何地方找到正式记录。