【发布时间】:2022-11-11 05:52:42
【问题描述】:
我有以下代码:
using MyBlazorApp.Server.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
namespace MyBlazorApp.Server.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole<Guid>, Guid>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>()
.Property(e => e.firstName)
.HasMaxLength(250);
modelBuilder.Entity<ApplicationUser>()
.Property(e => e.lastName)
.HasMaxLength(250);
modelBuilder.Entity<ApplicationUser>()
.Property(e => e.isLdapLogin);
modelBuilder.Entity<ApplicationUser>()
.Property(e => e.isMFAforce);
modelBuilder.Entity<ApplicationUser>()
.Property(e => e.apiKey);
modelBuilder.Entity<ApplicationUser>()
.Property(e => e.IsEnabled);
//Seeding a 'Administrator' role to AspNetRoles table
var arId = "dffc6dd5-b145-41e9-a861-c87ff673e9ca";
modelBuilder.Entity<IdentityRole>().HasData(
new IdentityRole
{
Id = arId,
Name = "Admins",
NormalizedName = "ADMINS".ToUpper(),
ConcurrencyStamp = arId
}
); ;
var urId = "f8a527ac-d7f6-4d9d-aca6-46b2261b042b";
modelBuilder.Entity<IdentityRole>().HasData(
new IdentityRole
{
Id = urId,
Name = "Users",
NormalizedName = "USERS".ToUpper(),
ConcurrencyStamp = urId
}
); ;
//a hasher to hash the password before seeding the user to the db
var hasher = new PasswordHasher<IdentityUser>();
//Seeding the Admin User to AspNetUsers table
modelBuilder.Entity<ApplicationUser>().HasData(
new ApplicationUser
{
Id = new Guid("6fbfb682-568c-4f5b-a298-85937ca4f7f3"), // primary key
UserName = "super.admin",
NormalizedUserName = "SUPER.ADMIN",
PasswordHash = hasher.HashPassword(null, "7ugVUczrm7"),
firstName = "Super",
lastName = "Admin",
Email = "super.admin@local.app",
NormalizedEmail = "SUPER.ADMIN@LOCAL.APP",
EmailConfirmed = true,
isMFAforce = 0,
isLdapLogin = 0
}
);
List<IdentityUserRole<string>> UserRoles = new List<IdentityUserRole<string>>();
UserRoles.Add(new IdentityUserRole<string>
{
RoleId = "dffc6dd5-b145-41e9-a861-c87ff673e9ca",
UserId = "6fbfb682-568c-4f5b-a298-85937ca4f7f3"
});
modelBuilder.Entity<IdentityUserRole<string>>().HasData(UserRoles);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
}
}
当我点击命令dotnet ef migrations add IntitialMigration 时,我收到以下错误:实体类型“IdentityUserRole”需要定义一个主键。
我已经找到了必须使用 base.OnModelCreating(modelBuilder); 的最首选解决方案。但正如您在我的代码中看到的那样,我已经使用了它。
我希望有人知道为什么会抛出这个错误。
【问题讨论】:
标签: c# entity-framework-core blazor asp.net-identity