【发布时间】:2013-11-25 21:16:23
【问题描述】:
控制器:
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;
}
}
数据库表:
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);
上面的代码列出了我正在处理的所有类。在运行我的应用程序时收到错误:
“在模型生成期间检测到一个或多个验证错误”以及“实体类型未定义键”。
【问题讨论】:
-
检查存储库文件。此页面中的所有解决方案都很棒,但就我而言,我做的一切都是正确的,但忘记将表声明为 DbSet 并将其添加到 modelbuilder.configurations。
-
在我的情况下,我将代码指向另一个数据库,而数据库中缺少该表
标签: c# .net entity-framework