标签:
接下来用学生这个例子来演示,有学生表,课程表,和成绩表三张表
首先是Model层
学生表
using System; using System.Collections.Generic; using System.Linq; using System.Web; /**/ using System.ComponentModel.DataAnnotations;//验证 namespace CodeFirstDemo.Models { public class Student { [Key] public int Id { get; set; } [Required] [StringLength(50)] public string Name { get; set; } } }
课程表
using System; using System.Collections.Generic; using System.Linq; using System.Web; /**/ using System.ComponentModel.DataAnnotations;//验证 namespace CodeFirstDemo.Models { public class Course { [Key] public int Id { get; set; } [Required] [StringLength(50)] public string Name { get; set; } } }
成绩表
using System; using System.Collections.Generic; using System.Linq; using System.Web; /**/ using System.ComponentModel.DataAnnotations;//验证 namespace CodeFirstDemo.Models { public class Score { [Key] public int Id { get; set; } public Student Student { get; set; } public Course Course { get; set; } } }
[Key]表示在数据库中该字段为主键,[Required]表示不为空,[StringLength]也就是长度了
这一步完成之后,我们要建立一个StudentInfoEntities的类,这个类要继承自DbContext,而DbContext类在System.Data.Entity命名空间下,需引用EntityFramework.dll类库,
如安装不了,可以去Visual Studio Gallery下载,其实,只需要引用一个叫做Entity Framework的dll类库即可
StudentInfoEntities类
using System; using System.Collections.Generic; using System.Linq; using System.Web; /**/ using System.Data.Entity; namespace CodeFirstDemo.Models { public class StudentInfoEntities:DbContext { public DbSet<Course> Courses { get; set; } public DbSet<Score> Scores { get; set; } public DbSet<Student> Students { get; set; } } }
接着,我们在Web.Config里配置一下数据库的连接字符串
<connectionStrings> <add name="StudentInfoEntities" connectionString="Data Source=.\SQLEXPRESS; User=test;Password=test;Initial Catalog=StudentInfo;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings>
最后,新建一个HomeController
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; /**/ using CodeFirstDemo.Models; namespace CodeFirstDemo.Controllers { public class HomeController : Controller { private StudentInfoEntities db = new StudentInfoEntities(); public string Index() { var data = db.Students.ToList(); return "Database is build success!"; } } }
点击调试,触发一下,查看数据库
同时,您会发现,在Score表中,自动产生外键关系
标签:
原文地址:http://www.cnblogs.com/lvdongjie/p/5579570.html