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

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();

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.


Using Identity in ASP .NET,id are automatically generated in db (uniqueidentifier data type). In C# you can generate GUID using method Guid.NewGuid()

A GUID is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required. Such an identifier has a very low probability of being duplicated.

Here you find C# and T-SQL


EF isn't generating that value. That's a GUID (uniqueidentifier in T-SQL) value which is auto-generated by SQL Server when a new row is INSERTed,.