The entity type 'Microsoft.AspNetCore.Mvc.Rendering.SelectListGroup' requires a primary key to be defined

Viewed 4527

New to .Net Core.

Trying to implement a dropdown list similar to: MVC6 Dropdownlist of Countries

In my model class I have

public SelectList SiteList { get; set; }

In my controller, I have:

var sites = _context.Site.OrderBy(s => s.Name).Select(x => new { Id = x.ID, Value = x.Name });

    var model = new Issue();
    model.SiteList = new SelectList(sites, "Id", "Value");

    return View(model);

In my view, I have:

<td class="input-item">
<select asp-for="SiteID" asp-items="@Model.SiteList"></select>
</td>

When I try to implement a migration, I get the following error: The entity type 'Microsoft.AspNetCore.Mvc.Rendering.SelectListGroup' requires a primary key to be defined.

I tried ignoring in my Migrations namespace:

modelBuilder.Entity<Issue>().Ignore(i => i.SiteList);

But I'm not entirely sure that I've done this in the right spot.

2 Answers

I've run into this issue before. My problem ended up being that while coding my controller I accidentally generated a DbSet for my view model with the List<SelectListItem> on it at the bottom of my ApplicationDbContext.cs file. The [NotMapped] "fix" is more of a band-aid to the problem than actually solving what's causing the error.

Check around your ApplicationDbContext.cs file for a DbSet of the view model that has your List<SelectListItem> on it and remove it.

It should look something like this:
public DbSet<TodoItemViewModel> TodoItemViewModel { get; set; }

Related