为了支持以设计为中心的开发流程, EF 推出了以代码为中心的模式 code first. 我们称之为代码优先开发, 代码优先的开发支持更加优美的开发流程, 允许在不使用设计器或者定义一个 xml 映射文件的情况下进行开发. 对数据库的操作不需要通过 sql 语句完成.
在 MVC 中使用 code first
1, 添加引用 EntityFramework.dll 和针对于 sql server 数据库的 EntityFarmework.SqlServer.dll 文件
2, 在 web.config 文件中添加数据库连接字符串
3, 数据访问层指向配置文件
- namespace DAL
- {
- public class MyContent:DbContext
- {
- public MyContent() : base("name=XXX")
- {
- }
- public DbSet<StudentInfo> stu { get; set; }
- }
- }
4, 实现数据操作
- public class StudentDal : IDataServer<StudentInfo>
- {
- MyContent myc = new MyContent();
- public int Create(StudentInfo t)
- {
- myc.stu.Add(t);
- return myc.SaveChanges();
- }
- public int Delete(int id)
- {
- var stu = myc.stu.Where(m=>m.Id==id).FirstOrDefault();
- myc.Entry(stu).State = System.Data.Entity.EntityState.Deleted;
- return myc.SaveChanges();
- }
- public List<StudentInfo> GetAll()
- {
- return myc.stu.ToList();
- }
- public StudentInfo GetAllById(int id)
- {
- return myc.stu.Where(m => m.Id == id).FirstOrDefault();
- }
- public int Update(StudentInfo t)
- {
- myc.Entry(t).State = System.Data.Entity.EntityState.Modified;
- return myc.SaveChanges();
- }
- }
来源: http://www.bubuko.com/infodetail-2996335.html