gpt4 book ai didi

c# - 为什么不使用 Entity Framework 创建代码优先表?

转载 作者:行者123 更新时间:2023-11-30 12:43:54 25 4
gpt4 key购买 nike

又一个 ASP MVC 传奇 tutorial我正在努力。一切都进行得很顺利,除了,我注意到正在创建的三个表中有两个没有数据。无法弄清楚为什么,我认真地删除了数据库,以为我会让它从头开始重新创建。好吧,现在数据库已创建,但其中没有表。并且,表中的数据仍会传递到 View 。我很困惑。

SchoolContext.cs

public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
....
....

SchoolInitializer.cs

public class SchoolInitializer : DropCreateDatabaseIfModelChanges<SchoolContext>
{
protected override void Seed(SchoolContext context)
{
var students = new List<Student>()
{
new Student{FirstName = "James", LastName = "Dean", EnrollmentDate = DateTime.Parse("01/01/2015")},
new Student{FirstName = "Linda", LastName = "Thames", EnrollmentDate = DateTime.Parse("01/01/2015")}
};

foreach (var student in students)
{
context.Students.Add(student);
}
context.SaveChanges();

...And a Courses table and an Enrollment table...

XyzController.cs

public class XyzController : Controller
{
private SchoolContext db = new SchoolContext();
// GET: Xyz
public ActionResult Abc()
{
var students = db.Students.ToList();

Student data is passed to view

But no tables in the DB

最佳答案

您是否正确设置了数据库初始化程序?您将需要这样的东西:

Database.SetInitializer(new DropCreateDatabaseAlways<BlogContext>());

您应该将这一行放在 Global.asax 的 Application_Start() 方法中如果是,您可以回收您的应用程序池以使此代码再次运行。

关于c# - 为什么不使用 Entity Framework 创建代码优先表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30041753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com