EntityFramework.dll中出现“System.InvalidOperationException”类型的exception,但未在用户代码中处理
我正在尝试为部门名称制作下拉列表。 我正在使用MVC5。 我在堆栈溢出上看到了太多的解决方案,但我从未找到与MVC5相关的有价值的解决方案。
Database Name : AppraisalDBContext Table Name : Department Column Name : deptID (Primarykey) deptName (department name) Description
我收到此错误:
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code Additional information: The model backing the 'AppraisalDBContext' context has changed since the database was created.Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?
码:
控制器类名称(DepartmentController.cs):
public ActionResult Index(string depName) { var DeptLst = new List(); var GenreQry = from d in db.Department orderby d.deptName select d.deptName; DeptLst.AddRange(GenreQry); // Here I am confusing ViewBag.depName = new SelectList(DeptLst); // Here I am confusing var depts = from m in db.Department // Here I am confusing select m; return View(depts); }
模型类名称(Departments.cs):
namespace appraisalProject.Models { [Table("Department")] public class Departments { [Key] public int deptId { get; set; } public string deptName { get; set; } public string Description { get; set; } } }
模型类名称(AppraisalDBContext.cs):
namespace appraisalProject.Models { public class AppraisalDBContext:DbContext { public DbSet Department { get; set; } } }
Index.cshtml:
@using (Html.BeginForm()) { Genre: @Html.DropDownList("depts", "All")
}
错误消息详细说明了您需要知道的所有内容:
附加信息:自创建数据库以来,支持’AppraisalDBContext’上下文的模型已更改。请使用Code First Migrations更新数据库( http://go.microsoft.com/fwlink/ ?
这意味着AppraisalDBContext
使用的某个类已更改,但数据库尚未更新,因此现在已过时。 您需要使用Code First迁移进行更新。
这是一个很好的博客文章,引导您完成整个过程。
兰的回答帮助了我。 问题是,我更新了模型类,但数据库仍然是旧的定义。 我认为初始化程序ClearDatabaseSchemaIfModelChanges <>应该在新的调用上重置数据库,这就是我在msdn上读到的内容。 事实证明,初始化器不会被调用。 所以我手动删除数据库:
new MyDbContext().Database.Delete();
在WebApiConfig的register()Methode中。
之后,在下次启动时调用初始化程序,并更新db模式。