Reputation: 41
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.
controller code:
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; }
}
}
Upvotes: 2
Views: 15264
Reputation: 2880
Make sure that you have set the auto increment attribute to 'Emp_Id' column in your database table, and your model should look like this:
[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; }
}
Upvotes: 1
Reputation: 1293
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; }
}
Use [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
only if your database generate ids, if not you just [Key]
attribute.
Upvotes: 7