Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 316
coolhand Avatar asked Dec 23 '22 15:12

coolhand


1 Answers

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.

like image 62
coolhand Avatar answered Apr 06 '23 00:04

coolhand