我正在開發一個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();