Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using byte as the primary key datatype

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?

like image 222
user962926 Avatar asked Aug 30 '12 17:08

user962926


People also ask

What is byte data type in SQL?

The BYTE data type stores any kind of binary data in an undifferentiated byte stream. Binary data typically consists of digitized information, such as spreadsheets, program load modules, digitized voice patterns, and so on.


1 Answers

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.

like image 126
Slauma Avatar answered Sep 28 '22 02:09

Slauma