我使用代码优先的方法来创建架构,然后在 Seed 方法的帮助下填充其中的数据
我正在使用实体框架版本 5.0、SQLEXPRESS2008 和 MVC4
下面是我的模型
public enum Grade
{
A, B, C, D, F
}
public class Enrollment
{
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
[DisplayFormat(NullDisplayText = "No grade")]
public Grade? Grade { get; set; }
public virtual Course Course { get; set; }
public virtual Student Student { get; set; }
}
这就是我在 Intializer 中使用种子方法将数据填充到数据库的方式
var enrollments = new List<Enrollment>
{
new Enrollment{StudentID=1,CourseID=1050,Grade=Grade.A},
new Enrollment{StudentID=1,CourseID=4022,Grade=Grade.C},
new Enrollment{StudentID=1,CourseID=4041,Grade=Grade.B},
new Enrollment{StudentID=2,CourseID=1045,Grade=Grade.B},
new Enrollment{StudentID=2,CourseID=3141,Grade=Grade.F},
new Enrollment{StudentID=2,CourseID=2021,Grade=Grade.F},
new Enrollment{StudentID=3,CourseID=1050},
new Enrollment{StudentID=4,CourseID=1050,},
new Enrollment{StudentID=4,CourseID=4022,Grade=Grade.F},
new Enrollment{StudentID=5,CourseID=4041,Grade=Grade.C},
new Enrollment{StudentID=6,CourseID=1045},
new Enrollment{StudentID=7,CourseID=3141,Grade=Grade.A},
};
enrollments.ForEach(s => context.Enrollments.Add(s));
context.SaveChanges();
在调试时,我可以在该上下文中看到“等级”列中的数据
但它既不会在数据库中创建“等级”列,也不会填充其数据。
我在 web.config 中设置了 Context 和 Database Initalizer,如下所示
<entityFramework>
<context type="EntityFrameworkWithMVC.DAL.SchoolContext, EntityFrameworkWithMVC">
<databaseInitializer type="EntityFrameworkWithMVC.DAL.SchoolInitializer, EntityFrameworkWithMVC" />
</context>
</contexts>
</entityFramework>