我在ASP.Net Core 1.1中创建了一个新的Web应用程序,ASP.Net标识3的默认模板随附了nvarchar(400)
或字符串作为“Id”字段的默认数据类型。使用Uniqueidentifier重命名asp.net标识3(dbo.ASPNetxxx)中的默认表,并为ID重命名
我已经改变从nvarchar(400)
默认TKey
类型Uniqueidentifier
,有什么办法使用默认代码第一种方法来改变在asp.net身份默认dbo.ASPNetxxx表,自定义名称?
我在ASP.Net Core 1.1中创建了一个新的Web应用程序,ASP.Net标识3的默认模板随附了nvarchar(400)
或字符串作为“Id”字段的默认数据类型。使用Uniqueidentifier重命名asp.net标识3(dbo.ASPNetxxx)中的默认表,并为ID重命名
我已经改变从nvarchar(400)
默认TKey
类型Uniqueidentifier
,有什么办法使用默认代码第一种方法来改变在asp.net身份默认dbo.ASPNetxxx表,自定义名称?
我已经找到了答案在评论here和我想分享更多的在这里举办,感谢“拉斐尔加罗法洛”为回答这个问题,我抄答案,并加入我的2美分:
到重命名默认表中asp.net identity 3
和更改数据类型Uniqueidentifier
,使用以下步骤:
在ApplicationDbContext.cs:
更改ApplicationDbContext或任何你用来反映这一个:
改变类是:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>
和OnModelCreating
方法是:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customizations
builder.Entity<ApplicationUser>(i =>
{
i.ToTable("Users");
i.HasKey(x => x.Id);
});
builder.Entity<ApplicationRole>(i =>
{
i.ToTable("Roles");
i.HasKey(x => x.Id);
});
builder.Entity<IdentityUserRole<Guid>>(i =>
{
i.ToTable("UserRoles");
i.HasKey(x => new { x.RoleId, x.UserId });
});
builder.Entity<IdentityUserLogin<Guid>>(i =>
{
i.ToTable("UserLogins");
i.HasKey(x => new { x.ProviderKey, x.LoginProvider });
});
builder.Entity<IdentityRoleClaim<Guid>>(i =>
{
i.ToTable("RoleClaims");
i.HasKey(x => x.Id);
});
builder.Entity<IdentityUserClaim<Guid>>(i =>
{
i.ToTable("UserClaims");
i.HasKey(x => x.Id);
});
builder.Entity<IdentityUserToken<Guid>>(i =>
{
i.ToTable("UserTokens");
i.HasKey(x => x.UserId);
});
}
要为用户和角色的ID添加一个默认的GUID值:
builder.Entity<ApplicationUser>(b =>
{
b.Property(u => u.Id).HasDefaultValueSql("NEWID()");
});
builder.Entity<ApplicationRole>(b =>
{
b.Property(u => u.Id).HasDefaultValueSql("NEWID()");
});
我刚刚从名称中删除了ASPNet扩展名,您可以添加自定义表名。你可以替换Guid
与int
为整数ID
在ApplicationUser.cs我创建了一个自定义ApplicationUser类
public class ApplicationUser : IdentityUser<Guid>
{
}
和自定义ApplicationRole类
public class ApplicationRole : IdentityRole<Guid>
{
}
在Startup.cs下ConfigureServices
方法
更改您的ASP.NET核心启动根据:
services
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services
.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext, Guid>()
.AddDefaultTokenProviders();
删除Data/Migrations文件夹内的内容,但保留Migrations文件夹。
现在,在命令行(CMD),将目录更改为应用程序根:
CD X:\ApplicationPathHere
如果存在,删除现有的数据库,因为该模式不能从PK字符串迁移到PK的Guid
dotnet ef database drop -c ApplicationDbContext
创建初始迁移
dotnet ef migrations add InitialCreate -c ApplicationDbContext
创建数据库
dotnet ef database update
更新 对于.NET核2.0 MVC项目模板,
你可能会得到一些错误,在ManageController
,只需通过添加.ToString()
,无需通过INT投的ID或GUID为:
.AddEntityFrameworkStores<ApplicationDbContext, Guid>()
只是加上
.AddEntityFrameworkStores<ApplicationDbContext>()