ASP.net mvc 一直提示model没有Key 20C

这是 model 和 数据库上下文
public class Title
{
public int Tid { get; set; }
public string Tname { get; set; }
public int Tnumber { get; set; }
}
public class TitleDbContext : DbContext
{
public DbSet

Titles { get; set; }
}
控制器:
namespace Mydesign.Controllers
{
public class TitlesController : Controller
{
private TitleDbContext db = new TitleDbContext();
// GET: Titles
public ActionResult Index()
{
return View(db.Titles.ToList());
}
}
}

以及Index视图
@model IEnumerable

@{
ViewBag.Title = "Index";
}

@foreach (var item in Model) { }
@Html.DisplayNameFor(model => model.Tname) @Html.DisplayNameFor(model => model.Tnumber)
@Html.DisplayFor(modelItem => item.Tname) @Html.DisplayFor(modelItem => item.Tnumber) @Html.ActionLink("Edit", "Edit", new { id = item.Tid }) | @Html.ActionLink("Details", "Details", new { id = item.Tid }) | @Html.ActionLink("Delete", "Delete", new { id = item.Tid })

报错内容这个
发生了 System.Data.Entity.ModelConfiguration.ModelValidationException
HResult=0x80131500
Message=One or more validation errors were detected during model generation:

Mydesign.Models.Title: : EntityType 'Title' has no key defined. Define the key for this EntityType.
Titles: EntityType: EntitySet 'Titles' is based on type 'Title' that has no keys defined.

Source=<无法计算异常源>
StackTrace:
<无法计算异常堆栈跟踪>

4个回答

public int Tid { get; set; }
这个是主键么?加上[Key]

toby1123yjh
toby1123yjh 具体怎么做,百度说法不一,Model似乎不存在key,而且试了一下也没用
接近 2 年之前 回复

[Key]
public int Tid { get; set; }

[Key]
public int Tid { get; set; }

实体类里添加

去数据库里添加主键试一下

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!