EF Code First 知識點梳理
阿新 • • 發佈:2019-02-25
nag ble true mod require code conn var throw 談談對ēf的知識點梳理
0 安裝EntityFramework
install-package EntityFramework
配置連接:
<connectionStrings> <add name="connstr1" connectionString="Data Source=.\mssqlserver2012;Initial Catalog=ef8;User ID=xxx;Password=xxxx" providerName="System.Data.SqlClient" /> </connectionStrings>
1 codefirst方式: 模型先建立(poco) 值類型? 引用類型的空&非空區別
1 public class Student:BaseEntity 2 { 3 4 public string Name { get; set; } 5 public int Age { get; set; } 6 public int ClassId { get; set; } 7 public virtual Class Class { get; set; }View Code 2 先問一個問題 :為什麽 用 virtual 修飾model的導航屬性? 3 fluent api 方式 ( : EntityTypeConfiguration<Student>配置)8 9 10 、}
public class StudentConfig:EntityTypeConfiguration<Student> { public StudentConfig(){ ToTable("T_Students"); Property(sView Code=>s.Name).HasMaxLength(30).IsRequired().IsUnicode(false); HasRequired(s=>s.Class).WithMany().HasForeignKey(t=>t.ClassId); HasRequired(s => s.MinZhu).WithMany().HasForeignKey(t => t.MinZhuId); } }
4 一對多 多對多 表與表之間關系映射 has***with***HasForeignKey.Map(t=t.ToTable("t_sutenetsTeachersRelation").mapLeftKey("sid").mapRightKey("tid")). 建議在多端配置 5 ObjectStateManager 5個狀態理解 unchanged modified deleted added detached 修改到一個狀態->(明確當前入口在哪裏?)
- ctx.Entry("stu").State=EntityState.UnChanged
- 調用 attach方法(UnChanged)
- 調用 add方法
- 通過where等lamda 查詢到的對象狀態 停留在 Unchanged 狀態(修改 刪除可用)
1 public class CommonCRUD<T> where T : BaseEntity 2 { 3 private MyContext ctx { get; set; } 4 public CommonCRUD(MyContext ctx1) 5 { 6 this.ctx = ctx1; 7 } 8 9 //curd ... 10 11 public int AddNew(T t) 12 { 13 ctx.Set<T>().Add(t); 14 int key = ctx.SaveChanges(); 15 return key; 16 } 17 public int MarkDelete(int id) 18 { 19 T t1 = ctx.Set<T>().SingleOrDefault(t => t.Id == id && t.IsDelete == false); 20 if (t1 == null) 21 { 22 throw new ArgumentException("沒有找到!!!"); 23 } 24 ctx.Set<T>().Remove(t1); 25 int line = ctx.SaveChanges(); 26 return line; 27 } 28 29 public T GetById(int id) 30 { 31 T t1 = ctx.Set<T>().SingleOrDefault(t => t.Id == id && t.IsDelete == false); 32 if (t1 == null) 33 { 34 throw new ArgumentException("沒有找到!!!"); 35 } 36 return t1; 37 38 } 39 40 public IQueryable<T> GetAll(int start, int count) 41 { 42 // IQueryable好處: 43 // [0] 可以延遲加載 後 用 AsNoTracking().Include().Where().... 44 IQueryable<T> ts = ctx.Set<T>().OrderBy(t => t.CreateTime).Where(t => t.IsDelete == false).Skip(start).Take(count); 45 46 return ts; 47 } 48 49 public long GetCount() 50 { 51 return ctx.Set<T>().Where(t => t.IsDelete == false).LongCount(); 52 53 } 54 55 56 } 57CommonCRUD
ps 調用如下:
MyContext ctx = new MyContext(); CommonCRUD<Student> crud = new CommonCRUD<Student>(ctx); Student Student = crud.GetAll(0, 2).AsNoTracking().Include("Class").FirstOrDefault(); var ls = Student.Class.Name;
EF Code First 知識點梳理