.Net Core 2.2 Identity framework has string primary key which is an auto-generated GUID. My question is how to have an auto-generated STRING primary key using Entity Framework 2.2?
Asked
Active
Viewed 6,250 times
6

Kok How Teh
- 3,298
- 6
- 47
- 85
-
like generate a random string without any constraints (any length, any characters, etc)? – Jan Paolo Go May 17 '19 at 15:10
-
GUID but the type must be string. Not Guid. – Kok How Teh May 18 '19 at 02:40
-
Why do you want to have a property of type `string` instead of type `Guid` if you know/want the value to be a valid GUID? – Jan Paolo Go May 18 '19 at 03:45
-
I need a generic auto-generated VARCHAR primary key. GUID is a good fit but I don't want to limit to GUID type. – Kok How Teh May 18 '19 at 08:45
2 Answers
7
You need to have the attribute [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
added to the column. See the official documentation for more details.

Prakash G. R.
- 4,746
- 1
- 24
- 35
-
This does the trick: [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public string ID { get; set; } – Kok How Teh May 22 '19 at 01:44
4
Auto-generated primary key by using Fluent API
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Node>().Property(x => x.ID).HasDefaultValueSql("NEWID()");
}

SUNIL DHAPPADHULE
- 2,755
- 17
- 32