📅  最后修改于: 2020-11-21 07:35:56             🧑  作者: Mango
在Entity Framework中,Seed在EF 4.1中引入,可与数据库初始化程序一起使用。种子方法的一般想法是将数据初始化到由Code First创建或由Migrations演进的数据库中。此数据通常是测试数据,但也可能是参考数据,例如已知学生列表,课程等。初始化数据后,它将执行以下操作:
Seed方法将数据库上下文对象作为输入参数,并且该方法中的代码使用该对象将新实体添加到数据库中。要将数据播种到数据库中,您需要覆盖Seed方法。让我们看下面的示例,其中一些默认数据在内部类中初始化到数据库中。
private class UniDBInitializer : DropCreateDatabaseAlways {
protected override void Seed(MyContext context) {
IList students = new List();
students.Add(new Student() {
FirstMidName = "Andrew",
LastName = "Peters",
EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())
});
students.Add(new Student() {
FirstMidName = "Brice",
LastName = "Lambson",
EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())
});
students.Add(new Student() {
FirstMidName = "Rowan",
LastName = "Miller",
EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())
});
foreach (Student student in students)
context.Students.Add(student);
base.Seed(context);
}
}
在上面的代码中,学生表已初始化。您需要在上下文类中设置此数据库初始化器类,如以下代码所示。
public MyContext() : base("name=MyContextDB") {
Database.SetInitializer(new UniDBInitializer());
}
以下是MyContext类的完整类实现,其中还包含DB初始化程序类。
public class MyContext : DbContext {
public MyContext() : base("name=MyContextDB") {
Database.SetInitializer(new UniDBInitializer());
}
public virtual DbSet Courses { get; set; }
public virtual DbSet Enrollments { get; set; }
public virtual DbSet Students { get; set; }
private class UniDBInitializer : DropCreateDatabaseAlways {
protected override void Seed(MyContext context) {
IList students = new List();
students.Add(new Student() {
FirstMidName = "Andrew",
LastName = "Peters",
EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())
});
students.Add(new Student() {
FirstMidName = "Brice",
LastName = "Lambson",
EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())
});
students.Add(new Student() {
FirstMidName = "Rowan",
LastName = "Miller",
EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())
});
foreach (Student student in students)
context.Students.Add(student);
base.Seed(context);
}
}
}
编译并执行以上示例后,您可以在数据库中看到数据,如下图所示。
我们建议您逐步执行上述示例,以更好地理解。