Dil*_*ip 2 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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的模范员工类:
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; }
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的员工上下文类:
namespace MVCApplication.Models
{
public class EmployeeContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
您必须将属性设置[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; }
}
Run Code Online (Sandbox Code Playgroud)
使用[DatabaseGenerated(DatabaseGeneratedOption.Identity)]只有当你的数据库生成的ID,如果你不只是[Key]属性.
| 归档时间: |
|
| 查看次数: |
10735 次 |
| 最近记录: |