Not sure what happened but I am getting the following error while attempting to pull up any view in my web app. The code is auto generated by visual studio and I am not getting any errors before building. Using ASP.Net MVC 6, EF7.
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.Core.dll but was not handled in user code
Additional information: The entity type 'Microsoft.AspNet.Mvc.Rendering.SelectListGroup' requires a key to be defined.
Here is the line the code is erroring out on.
public IActionResult Index()
{
var schoolContext = _context.Schools
.Include(s => s.District)
.Include(s => s.Location)
.Include(s => s.Tier);
return View(schoolContext.ToList());
}
After some searching I can't figure out exactly what I need to fix. This was working at one point. Not sure what changed.
The view does have a defenition
@model IEnumerable<School>
As requested here is the School model
public class School
{
//Original Fields
public int SchoolId { get; set; }
[Display(Name = "Name")]
public string SchoolName { get; set; }
[Display(Name = "Date Added")]
public DateTime SchoolDateAdded { get; set; }
[Display(Name = "Last Update")]
public DateTime SchoolLastUpdate { get; set; }
[Display(Name="Updated By")]
public string SchoolUpdatedBy { get; set; }
//Referance Fields
public int DistrictId { get; set; }
public IEnumerable<SelectListItem> DistrictList { get; set; }
public int LocationId { get; set; }
public IEnumerable<SelectListItem> LocationList { get; set; }
public int TierId { get; set; }
public IEnumerable<SelectListItem> TierList { get; set; }
//Navigation Property
public District District { get; set; }
public Location Location { get; set; }
public Tier Tier { get; set; }
}
These IEnumerable<SelectListItem>
s should not be part of your EF model. Remember the single responsibility principle. Keep any UI framework away from your DAL implementation. Use a view model representing a School
.
As for the error, from EF's point of view, School
has a 1-n association with SelectListItem
, so it tries to make it part of its mapping schema. But each mapped type needs a primary key, which of course isn't mapped, and EF can't infer any.
A quick, but dirty, fix would be to exclude the properties from being mapped by the [NotMapped]
attribute, but a better segregation of your code is the real remedy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With