EntityFramework.dll中出现'System.Data.Entity.ModelConfiguration.ModelValidationException'类型的异常

时间:2016-04-04 14:47:58

标签: asp.net-mvc asp.net-mvc-4

错误 - EntityFramework.dll中发生了'System.Data.Entity.ModelConfiguration.ModelValidationException'类型的异常,但未在用户代码中处理 附加信息:在模型生成期间检测到一个或多个验证错误: MVCApplication.Models.Employee :: EntityType'Employee'没有定义键。定义此EntityType的键。 员工:EntityType:EntitySet'Employees'基于没有定义键的'Employee'类型。

控制器代码:

namespace MVCApplication.Controllers
{
    public class EmployeeController : Controller
    {
        // GET: Employee
        public ActionResult Detail(int id)
        {
            EmployeeContext employeecontext = new EmployeeContext();
            Employee emp = employeecontext.Employees.Single(x => x.Emp_Id ==id);//here its throwing an exception
            return View("employee",emp);
        }
    }

这是我的模范员工类:

namespace MVCApplication.Models
{
    [Table("Employee")]
    public class Employee
    {
        public int Emp_Id { get; set; }
        public string Emp_Name { get; set; }
        public string Designation { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
    }
}

这是我的员工上下文类:

namespace MVCApplication.Models
{
    public class EmployeeContext : DbContext
    {
        public DbSet<Employee> Employees { get; set; }
    }
}

2 个答案:

答案 0 :(得分:5)

您必须将属性[Key]设置为您的模型,例如

[Table("Employee")]
public class Employee
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int Emp_Id { get; set; }
    public string Emp_Name { get; set; }
    public string Designation { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Country { get; set; }
}

仅当您的数据库生成ID时才使用[DatabaseGenerated(DatabaseGeneratedOption.Identity)],如果不是[Key]属性,则使用{{1}}。

答案 1 :(得分:1)

确保您已将自动增量属性设置为&#39; Emp_Id&#39;数据库表中的列,您的模型应如下所示:

[Table("Employees")]
public class Employee
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int Emp_Id { get; set; }
    public string Emp_Name { get; set; }
    public string Designation { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Country { get; set; }
}