我正在开发一个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; }
...
}
答案 0 :(得分:0)
在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();