Sto lavorando ad un progetto 2.0 asp.net-core.
Questo progetto contiene un database con Entity Framework Core. Sto lavorando sulla modalità Code First con le migrazioni.
Quello che voglio fare è creare alcuni dati predefiniti nel mio database sulla creazione della struttura.
Devo creare un utente.
Ho esaminato la funzione OnModelCreating nella mia classe IdentityDbContext ma non ho modo di accedere all'oggetto userManager.
Quindi non so come fare .... Grazie
Ecco il mio codice:
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; }
...
}
La convenzione di inizializzazione dei dati nella classe DbInitialize non nel metodo modelCreating. Il modo maggiormente utilizzato con modelCreating è quello di mappare le entità alle tabelle del database come il seguente codice.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Course>().ToTable("Course");
modelBuilder.Entity<Enrollment>().ToTable("Enrollment");
modelBuilder.Entity<Student>().ToTable("Student");
}
Successivamente, puoi creare una classe per il tuo oggetto fittizio.
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();