实体类型'Microsoft.AspNetCore.Mvc.Rendering.SelectListGroup'需要定义主键 [英] The entity type 'Microsoft.AspNetCore.Mvc.Rendering.SelectListGroup' requires a primary key to be defined

查看:139
本文介绍了实体类型'Microsoft.AspNetCore.Mvc.Rendering.SelectListGroup'需要定义主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.Net Core的新功能.

New to .Net Core.

尝试实现类似于以下内容的下拉列表: MVC6国家/地区下拉列表

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

在我的模型课上,

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

我认为,我有:

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

当我尝试实施迁移时,出现以下错误: 实体类型'Microsoft.AspNetCore.Mvc.Rendering.SelectListGroup'需要定义主键.

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.

我尝试忽略我的Migrations命名空间:

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.

推荐答案

要解决此问题,只需输入

In order to fix this, simply put

[NotMapped]

在.cs文件模型中SelectList属性上方:

above the SelectList property within the model .cs file:

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

这可防止EntityFramework将列表映射到模型.由于它不是模型数据库的一部分,因此不需要主键.

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.

这篇关于实体类型'Microsoft.AspNetCore.Mvc.Rendering.SelectListGroup'需要定义主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆