How to use String property as primary key in Entity Framework

c# database entity-framework entity-framework-6 sql


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.

I have a property

public string FooId { get; set; }

which is my primary key for the model.

But if I run the

PM> Update-Database

command in package manager console to update pending migrations to the database i get the following error:

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.

If I change the PK in my model to

public int FooId { get; set; } 

everything works fine.

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.

Is it really that I can't use a string as PK on a SQL database?

Or is there a way to do that?

5/23/2017 11:46:38 AM

Accepted Answer

This is the proper way of creating a PK without Identity Autoincrement enabled:

public string FooId { get; set; }
10/7/2015 4:03:59 AM

Popular Answer

If you need your primary key to be a string, then don't make it an identity column. Identity columns will generate primary key values for you, which you should turn off if you intend to generate the values yourself.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow