EntityFramework.dll中出现"System.InvalidOperationException"类型的异常,但未在用户代码中处理

Anu*_*ain 5 c# asp.net asp.net-mvc-4

我正在尝试为部门名称制作下拉列表.我正在使用MVC5.我在堆栈溢出上看到了太多的解决方案,但我从未找到与MVC5相关的有价值的解决方案.

Database Name : AppraisalDBContext
Table Name :  Department
Column Name : deptID (Primarykey)
              deptName (department name)
              Description 
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

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/?
Run Code Online (Sandbox Code Playgroud)

码:

控制器类名称(DepartmentController.cs):

public ActionResult Index(string depName)
{
    var DeptLst = new List<string>();          
    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);
}
Run Code Online (Sandbox Code Playgroud)

模型类名称(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; }
     }
}
Run Code Online (Sandbox Code Playgroud)

模型类名称(AppraisalDBContext.cs):

namespace appraisalProject.Models
{
    public class AppraisalDBContext:DbContext
    {
        public DbSet<Departments> Department { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

Index.cshtml:

@using (Html.BeginForm())
{
<p>
    Genre: @Html.DropDownList("depts", "All")
    <input type="submit" value="Filter" />
</p>
}
Run Code Online (Sandbox Code Playgroud)

Ian*_*Ian 7

错误消息详细说明了您需要知道的所有内容:

附加信息:自创建数据库以来,支持'AppraisalDBContext'上下文的模型已更改.请使用Code First Migrations更新数据库(http://go.microsoft.com/fwlink/

这意味着您使用的其中一个类AppraisalDBContext已更改,但数据库尚未更新,因此现在已过时.您需要使用Code First迁移进行更新.

这是一个很好的博客文章,引导您完成整个过程.