gpt4 book ai didi

asp.net-core - 在 EF 核心的 OnModelCreating 中创建一个用户和角色

转载 作者:行者123 更新时间:2023-12-05 07:38:49 30 4
gpt4 key购买 nike

我正在做一个 asp.net-core 2.0 项目。

该项目包含一个带有 Entity Framework Core 的数据库。我正在使用带有迁移的 Code First 模式。

我想做的是在我的数据库中创建一些关于结构创建的默认数据。

我需要创建一个用户。

我查看了我的 IdentityDbContext 类中的 OnModelCreating 函数,但我无法访问 userManager 对象。

所以我不知道该怎么做....谢谢

这是我的代码:

    public class MyContext : IdentityDbContext<Utilisateurs>
{
public static string ConnectionString;

public MyContext()
{

}

public MyContext(DbContextOptions<pluginwebContext> options) : base(options)
{

}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(MyContext.ConnectionString);
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var user = new MyUserClass { UserName = "test" };

// Error There
var result = await _userManager.CreateAsync(user, "1234");
}

public DbSet<MyTable1> table1 { get; set; }
...
}

最佳答案

在 DbInitialize 类中而不是在 modelCreating 方法中初始化数据的约定。使用 modelCreating 最常用的方法是将您的实体映射到数据库表,如以下代码。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Course>().ToTable("Course");
modelBuilder.Entity<Enrollment>().ToTable("Enrollment");
modelBuilder.Entity<Student>().ToTable("Student");
}

稍后,您可以为虚拟对象创建一个类。

  public static class DbInitializer
{
public static void Initialize(SchoolContext context)
{
//context.Database.EnsureCreated();

// Look for any students.
if (context.Students.Any())
{
return; // DB has been seeded
}

var courses = new Course[]
{
new Course {CourseID = 1050, Title = "Chemistry", Credits = 3,
DepartmentID = departments.Single( s => s.Name == "Engineering").DepartmentID
},
new Course {CourseID = 4022, Title = "Microeconomics", Credits = 3,
DepartmentID = departments.Single( s => s.Name == "Economics").DepartmentID
},
new Course {CourseID = 4041, Title = "Macroeconomics", Credits = 3,
DepartmentID = departments.Single( s => s.Name == "Economics").DepartmentID
},
new Course {CourseID = 1045, Title = "Calculus", Credits = 4,
DepartmentID = departments.Single( s => s.Name == "Mathematics").DepartmentID
},
new Course {CourseID = 2042, Title = "Literature", Credits = 4,
DepartmentID = departments.Single( s => s.Name == "English").DepartmentID
},
};

foreach (Course c in courses)
{
context.Courses.Add(c);
}
context.SaveChanges();

关于asp.net-core - 在 EF 核心的 OnModelCreating 中创建一个用户和角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47567822/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com