I am using entity-framework in mvc. I am receiving this error while generating view.I am using MVC controller with read/write actions and views, using EF. I am Trying to generate a list using scaffold template.
This Entity Framework auto generated class
namespace WebApplication3.Models
{
using System;
using System.Collections.Generic;
public partial class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
public Nullable<System.DateTime> DOB { get; set; }
public Nullable<int> DepartmentId { get; set; }
public virtual TblDepartment TblDepartment { get; set; }
}
}
Here is my Controller Code :
public ActionResult EmployeesByDep()
{
var employees = db.Employees.Include("TblDepartment").GroupBy(x => x.TblDepartment.DepName)
.Select(y => new TotalDepartments
{
DepName = y.Key,
Total = y.Count()
}
).ToList().OrderByDescending(y=>y.Total);
return View(employees);
}
Model Code:
public string DepName { get; set; }
public int Total { get; set; }
The problem is because you had not declared a key.
You should create a new class EmployeeMetaData.cs
With:
[MetadataType(typeof(EmployeeMetaData))]
public partial class Employee
{
}
public class Employee
{
[Key]
public int EmployeeId { get; set; }
}
add: using System.ComponentModel.DataAnnotations
;