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

情到浓时终转凉″ 提交于 2020-05-09 06:03:07

问题


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.


回答1:


In order to fix this, simply put

[NotMapped]

above the SelectList property within the model .cs file:

[NotMapped]
public SelectList SiteList { get; set; }

This prevents EntityFramework from mapping the list to the model. Since it's not part of the model database, it doesn't require a primary key.




回答2:


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; }



来源:https://stackoverflow.com/questions/45719579/the-entity-type-microsoft-aspnetcore-mvc-rendering-selectlistgroup-requires-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!