最佳答案
控制器:
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 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(null);
上面的代码列出了我正在处理的所有类:
“在模型生成期间检测到一个或多个验证错误”以及“实体类型没有定义键”。