使用字节作为主键数据类型 [英] Using byte as the primary key datatype

查看:224
本文介绍了使用字节作为主键数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是我到目前为止有:

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

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

如果我更改(在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.

这篇关于使用字节作为主键数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆