EF5.0區別於EF4.0的增刪改寫法


// 實現對數據庫的添加功能,添加實現EF框架的引用 40 41 public T AddEntity(T entity) 42 43 { 44 45 // EF4.0的寫法 添加實體 46 47 // db.CreateObjectSet<T>().AddObject(entity); 48 49 // EF5.0的寫法 50 51 db.Entry <T>(entity).State = EntityState.Added; 52 53 54 55 // 下面的寫法統一 56 57 db.SaveChanges(); 58 59 return entity; 60 61 } 62 63 64 65 // 實現對數據庫的修改功能 66 67 public bool UpdateEntity(T entity) 68 69 { 70 71 // EF4.0的寫法 72 73 // db.CreateObjectSet<T>().Addach(entity); 74 75 // db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified); 76 77 // EF5.0的寫法 78 79 db.Set <T> ().Attach(entity); 80 81 db.Entry <T>(entity).State = EntityState.Modified; 82 83 84 85 return db.SaveChanges() > 0 ; 86 87 } 88 89 90 91 // 實現對數據庫的刪除功能 92 93 public bool DeleteEntity(T entity) 94 95 { 96 97 // EF4.0的寫法 98 99 // db.CreateObjectSet<T>().Addach(entity); 100 101 // db.ObjectStateManager.ChangeObjectState(entity, EntityState.Deleted); 102 103 // EF5.0的寫法 104 105 db.Set <T> ().Attach(entity); 106 107 db.Entry <T>(entity).State = EntityState.Deleted; 108 109 110 111 return db.SaveChanges() > 0 ; 112 113 } 114 115 116 117 // 實現對數據庫的查詢 --簡單查詢 118 119 public IQueryable <T> LoadEntities(Func <T, bool> whereLambda) 120 121 { 122 123 // EF4.0的寫法 124 125 // return db.CreateObjectSet<T>().Where<T>(whereLambda).AsQueryable(); 126 127 // EF5.0的寫法 128 129 return db.Set <T>().Where <T> (whereLambda).AsQueryable(); 130 131 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM