Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Entity Framework generate a GUID for a primary key value?

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?

like image 804
Shivam Sharma Avatar asked Dec 21 '16 13:12

Shivam Sharma


2 Answers

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.

like image 74
Mujahid Daud Khan Avatar answered Oct 02 '22 14:10

Mujahid Daud Khan


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 :

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid Id { get; set; }

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

var id = Guid.NewGuid();
like image 28
PMerlet Avatar answered Oct 02 '22 15:10

PMerlet