EntityFramework.dll中发生类型为'System.Data.Entity.ModelConfiguration.ModelValidationException'的异常 [英] An exception of type 'System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll
问题描述
错误-EntityFramework.dll中发生类型为'System.Data.Entity.ModelConfiguration.ModelValidationException'的异常,但未在用户代码中处理 附加信息:在模型生成过程中检测到一个或多个验证错误: MVCApplication.Models.Employee::EntityType'Employee'未定义键.定义此EntityType的键. 员工:EntityType:EntitySet员工"基于未定义键的员工"类型.
Error-An exception of type 'System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll but was not handled in user code Additional information: One or more validation errors were detected during model generation: MVCApplication.Models.Employee: : EntityType 'Employee' has no key defined. Define the key for this EntityType. Employees: EntityType: EntitySet 'Employees' is based on type 'Employee' that has no keys defined.
控制器代码:
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);
}
}
这是我的模范员工班级:
this is my model employee class:
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; }
}
}
这是我的员工上下文类:
this is my employee context class:
namespace MVCApplication.Models
{
public class EmployeeContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
}
推荐答案
您必须像这样将属性[Key]
设置到模型中
You have to set attribute [Key]
to your model, like this
[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]
属性.
Use [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
only if your database generate ids, if not you just [Key]
attribute.
这篇关于EntityFramework.dll中发生类型为'System.Data.Entity.ModelConfiguration.ModelValidationException'的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!