我正在尝试将 Users 表的 ID 从字符串 (GUID) 更改为 int 并且非常困难。我看过很多示例,但它们似乎适用于早期版本的 Identity 或 vs,并且由于多种原因它们不起作用。
我要么得到一个编译器错误
'Microsoft.AspNetCore.Identity.IdentityUser', on 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore 6[TUser,TContext,TKey,TUserClaim,TUserLogin,TUserToken]' violates the constraint of type 'TUser'.
或者当我创建迁移时,我仍然得到 ID 的字符串列,而不是我预期的 int。
我使用的是 vs2019。 Asp.Net.Core 2.2 和 Microsoft.AspNetCore.Identity 2.2
有人能帮帮我吗?谢谢!
最佳答案
首先如下扩展IdenityUser
类,这样就可以添加自定义属性了:
public class ApplicationUser : IdentityUser<int>
{
}
如果您也在应用程序中使用 Role
,则扩展 IdentityRole
类。即使您不想使用它,您也可以安全地保存它:
public class ApplicationRole : IdentityRole<int>
{
}
现在您的 ApplicationDbContext
应该如下所示:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
现在在 Startup
类的 ConfigureServices
方法中如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
}
工作完成!现在运行一个全新的迁移并应用它。
关于entity-framework - ASP.Net.Core 2.2 身份更改 ID 从字符串到 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58147591/