How to use String property as primary key in Entity Framework

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.


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

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string FooId { get; set; }

What is your reason for having a string as a primary key?

I would just set the primary key to an auto incrementing integer field, and put an index on the string field.

That way if you do searches on the table they should be relatively fast, and all of your joins and normal look ups will be unaffected in their speed.

You can also control the amount of the string field that gets indexed. In other words, you can say "only index the first 5 characters" if you think that will be enough. Or if your data can be relatively similar, you can index the whole field.