EntityFramework - Code First - 实体映射到数据库
DEMO
安装EntityFramework,引用EntityFramework.dll
在Model中新建两个类,作为实体
class Teacher { public int ID { get; set; } public int Name { get; set; } } class Student { public int ID { get; set; } public int Name { get; set; } }
在Model中新建一个类,作为数据库上下文
public class DEMOContext : DbContext { public DbSet<Teacher> Teachers{ get; set; } public DbSet<Student> Students{ get; set; } }
在 web.config中添加链接字符串
<!-- name属性的值必须与继承自DbContext的类名一致,这样EntityFramework在web.config里才能找到正确的连接字符串,从而访问数据库。如果不写连接字符串,或者name的值不同,EF也会尝试连接本地的数据库,不过生成的数据库名,会是项目名.Models.StudentInfoEntities --> <connectionStrings> <add name="DEMOContext" connectionString="Data Source=.;Initial Catalog=DEMO_DB;Integrated Security=True" providerName="System.Data.SqlClient"/> </connectionStrings>
MVC中 在Controllers中添加控制器
public class TeacherController : Controller { private DEMOContext db = new DEMOContext(); public ActionResult Index() { return View(db.Teachers.ToList()); } } public class StudentController : Controller { private DEMOContext db = new DEMOContext(); public ActionResult Index() { return View(db.Students.ToList()); } }
在数据库中就能产生这两张表