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

33,572

Solution 1

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.

Solution 2

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

Solution 3

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

Solution 4

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,.

Share:
33,572
Shivam Sharma
Author by

Shivam Sharma

A passionate computer science student learning programming & cgi.

Updated on July 05, 2022

Comments

  • Shivam Sharma
    Shivam Sharma almost 2 years

    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?

  • Shivam Sharma
    Shivam Sharma over 7 years
    So when the user is created the EF generates this id or it generated by sql server automatically ?
  • Paul Hegel
    Paul Hegel over 3 years
    This approach makes it so I can set the value without the database. Which for my purpose is what I want, since I'm serializing to xml file