When we run the ASP.NET application and register the user, Entity Framework automatically sets the unique id (PK) in AspNetUser table:
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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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();
Method 2
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.
Method 3
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,.
Method 4
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.
Method 5
in EF core and poco:
...
.Property(p => p.Id)
.ValueGeneratedOnAdd()
;
Method 6
I think this is more a feature of SQL-Server, than of EF directly. EF creates the table with a unique-id field with identity on.
If you want to do that yourself, you need a unique-id field. Your object should then have a GUIDproperty Id, which you assign Guid.NewGuid()for instance.
Hope that helps
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0
