How does Entity Framework generate a GUID for a primary key value? c# entity-framework sql-server


When we run the ASP.NET application and register the user, Entity Framework automatically sets the unique id (PK) in AspNetUser table:

enter image description here

The same is true for other AspNetRoles, AspNetUserLogins, AspNetUserRoles except AspNetUserClaims which has identity enabled.

Can anybody explain how Entity framework create this unique Id? And if we want to create our own table with identity disabled in EF, how will we generate this kind of Id for primary key?

12/21/2016 2:01:00 PM

Accepted Answer

The GUID is not generated by Entity Framework nor by SQL. It is handled by Identity framework. Just navigate to IdentityModels.cs

public class ApplicationUser : IdentityUser
   // ...

This class is inherited from Microsoft.AspNet.Identity.EntityFramework.IdentityUser and constructor for this class is defined as (Source)

public IdentityUser()
    Id = Guid.NewGuid().ToString();

So GUID is generated in the constructor. This is same for other Identity tables too.

Note: Id Field is varchar (string) in database.

4/29/2018 5:36:48 PM

Popular Answer

This unique Id is created by SQL Server on insert.

If you want to let SQL Server generate the value on insert, you have to use the following attributes in your model :

public Guid Id { get; set; }

Or if you want to manage the Id by yourself, just generate it :

var id = Guid.NewGuid();

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