EF設計模式之code first
阿新 • • 發佈:2019-03-22
映射文件 width sql語句 ted fault pac ech return hang
為了支持以設計為中心的開發流程,EF推出了以代碼為中心的模式code first。我們稱之為代碼優先開發,代碼優先的開發支持更加優美的開發流程,允許在不使用設計器或者定義一個XML映射文件的情況下進行開發。對數據庫的操作不需要通過sql語句完成。
在MVC中使用code first
1、添加引用EntityFramework.dll和針對於sql server數據庫的EntityFarmework.SqlServer.dll文件
2、在Web.config文件中添加數據庫連接字符串
3、數據訪問層指向配置文件
namespace DAL { publicclass 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(); } }
EF設計模式之code first