实体框架如何为主键值生成GUID? [英] How does Entity Framework generate a GUID for a primary key value?

查看:187
本文介绍了实体框架如何为主键值生成GUID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们运行ASP.NET应用程序并注册用户时,Entity Framework会在AspNetUser表中自动设置唯一ID(PK):

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

其他AspNetRoles,AspNetUserLogins,AspNetUserRoles也是如此 除了AspNetUserClaims启用了身份.

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

有人可以解释实体框架如何创建此唯一ID吗?而且,如果我们要创建自己的表并在EF中禁用了身份,我们将如何为主键生成这种ID?

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?

推荐答案

GUID不是由Entity FrameworkSQL生成的.它由身份框架处理.只需导航到IdentityModels.cs

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
{
   // ...
}

此类从Microsoft.AspNet.Identity.EntityFramework.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();
}

因此在构造函数中生成了GUID.其他身份表也是如此.

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

注意:数据库中的ID字段为varchar (string).

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

这篇关于实体框架如何为主键值生成GUID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆