使用字节作为主键数据类型字节、数据类型、主键

2023-09-04 09:55:18 作者:蜜糖

我使用实体框架code-第一。我有一个表的不超过100行,我想使用的数据类型字节 TINYINT 在SQL Server )作为主键。

这是我到目前为止有:

  [重点]
公共字节ID {获得;组; }
 

问题是,当实体框架创建数据库,它不设置标识规范属性,使行自动递增的插入。

java基本数据类型作为类成员使用的默认值问题

如果我更改(在SQL Server SMALLINT )的数据类型为的Int16 一切都运行完美。

有没有办法告诉实体框架设置自动增量属性或者一个字节不能用作与实体框架code一主键?

解决方案

字节类型支持作为重点,并作为一个标识列。这是不默认为纪念字节的主键标识。但是,您可以覆盖这个默认的:

  [按键,DatabaseGenerated(DatabaseGeneratedOption.Identity)
公共字节ID {获得;组; }
 

设置身份选项明确是没有必要的 INT ,一个(也许更多类型?),但它是一个字节( = TINYINT 在SQL Server)。我理解了它通过测试,但找不到它的任何地方正式文件。

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.

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.

If I change the datatype to Int16 (smallint in SQL Server) everything works perfectly.

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?

解决方案

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.