控制器:using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using MvcApplication1.Models;using System.ComponentModel.DataAnnotations.Schema;namespace MvcApplication1.Controllers{ public class studentsController : Controller { // // GET: /students/ public ActionResult details() { int id = 16; studentContext std = new studentContext(); student first = std.details.Single(m => m.RollNo == id); return View(first); } }}DbContext模型:using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Data.Entity;namespace MvcApplication1.Models{ public class studentContext : DbContext { public DbSet<student> details { get; set; } }}模型:using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.ComponentModel.DataAnnotations.Schema;namespace MvcApplication1.Models{ [Table("studentdetails")] public class student { public int RollNo; public string Name; public string Stream; public string Div; }}數(shù)據(jù)庫表:CREATE TABLE [dbo].[studentdetails]( [RollNo] [int] NULL, [Name] [nvarchar](50) NULL, [Stream] [nvarchar](50) NULL, [Div] [nvarchar](50) NULL) 在global.asax.cs中Database.SetInitializer<MvcApplication1.Models.studentContext>(null);上面的代碼列出了我正在處理的所有類。在運行我的應(yīng)用程序時收到錯誤:“模型生成期間檢測到一個或多個驗證錯誤”以及“實體類型未定義鍵”。
3 回答

喵喔喔
TA貢獻1735條經(jīng)驗 獲得超5個贊
確保將學(xué)生班級的公共成員定義為帶有w的屬性{get; set;}(您是公共變量,這是一個常見錯誤)。
[Key]在所選屬性的頂部放置一個注釋。

心有法竹
TA貢獻1866條經(jīng)驗 獲得超5個贊
發(fā)生這種情況有多種原因。我在這里找到了其中一些,其他是我自己發(fā)現(xiàn)的。
如果該屬性的名稱不是Id,則需要為其添加[Key]屬性。
密鑰必須是屬性,而不是字段。
關(guān)鍵是 public
關(guān)鍵需要一個符合CLS的類型,這意味著無符號的類型,如uint,ulong等都是不允許的。
此錯誤也可能是由配置錯誤引起的。
- 3 回答
- 0 關(guān)注
- 665 瀏覽
添加回答
舉報
0/150
提交
取消