.NET基礎(chǔ)篇——Entity Framework 數(shù)據(jù)轉(zhuǎn)換層通用類
在實(shí)現(xiàn)基礎(chǔ)的三層開(kāi)發(fā)的時(shí)候,大家時(shí)常會(huì)在數(shù)據(jù)層對(duì)每個(gè)實(shí)體進(jìn)行CRUD的操作,其中存在相當(dāng)多的重復(fù)代碼。為了減少重復(fù)代碼的出現(xiàn),通常都會(huì)定義一個(gè)共用類,實(shí)現(xiàn)相似的操作,下面為大家介紹一下Entity Framework時(shí)常用到的通用類。
首先在數(shù)據(jù)庫(kù)建立起幾個(gè)關(guān)聯(lián)表:Person、Company、Position,三個(gè)實(shí)體之間通過(guò)導(dǎo)航屬性進(jìn)行相互引用。

下面為大家分別介紹以泛型實(shí)現(xiàn)的 Create、Read、Update、Delete 操作:
1. Create
在ObjectContext類之中,早已經(jīng)為大家預(yù)定了一個(gè)Create 的操作 AddObject:
void ObjectContext.AddObject(entitySetName string,object entity)
void ObjectSet<T>.AddObject(T entity)
1 public int Add<T>(T entity) where T : EntityObject 2 { 3 int changedCount = 0; 4 try 5 { 6 using (BasicArchitectureEntities context = new BasicArchitectureEntities()) 7 { 8 context.AddObject(typeof(T).Name, entity); 9 changedCount = context.SaveChanges(); 10 if (changedCount > 0) 11 context.AcceptAllChanges(); 12 } 13 } 14 catch (Exception ex) 15 { ........ } 16 return changedCount; 17 }
從下面的測(cè)試可以看到,ObjectContext.AddObject(entitySetName string,object entity)已相當(dāng)成熟,它不但可以加入單個(gè)實(shí)體,也可通過(guò)導(dǎo)航屬性,一次性加入多個(gè)關(guān)聯(lián)實(shí)體。
1 static void Main(string[] args) 2 { 3 BaseCommand command = new BaseCommand(); 4 //建立關(guān)聯(lián)實(shí)體 5 Company company = new Company() { CompanyName = "Sun" 6 ,Address="Beijing",Telephone="010-87654321"}; 7 Position position = new Position() { PositionName = "Project Manager" 8 , Salary = 15000.00, Company = company }; 9 //通過(guò)Add<T>同時(shí)加入實(shí)體對(duì)象company與position 10 int n=command.Add<Position>(position); 11 12 Console.ReadKey(); 13 }
若要使用批量插入,只要在AddObject方法前多加一個(gè)重復(fù)語(yǔ)言即可,在此就不再多作解釋了。
1 public int AddList<T>(List<T> entityList) where T : EntityObject 2 { 3 int changedCount = 0; 4 try 5 { 6 using (BasicArchitectureEntities context = new BasicArchitectureEntities()) 7 { 8 foreach (T entity in entityList) 9 context.AddObject(typeof(T).Name, entity); 10 changedCount = context.SaveChanges(); 11 if (changedCount > 0) 12 context.AcceptAllChanges(); 13 } 14 } 15 catch (Exception ex) 16 { ....... } 17 return changedCount; 18 }
2. Delete
同樣地,ObjectContext 類當(dāng)中也存在方法 ObjectContext.DeleteObject(object entity)用于刪除實(shí)體。
首先通過(guò)輸入的參數(shù) id 建立起EntityKey對(duì)象,然后在ObjectContext查找此實(shí)體,若實(shí)體存在則使用ObjectContext.DeleteObject(object entity)方法把此實(shí)體刪除 。
1 public int Delete<T>(int id) where T : EntityObject 2 { 3 int changedCount = 0; 4 try 5 { 6 using (BasicArchitectureEntities context = new BasicArchitectureEntities()) 7 { 8 //建立EntityKey對(duì)象 9 EntityKey entityKey = new EntityKey( 10 "BasicArchitectureEntities." + typeof(T).Name, "Id", id); 11 //通過(guò)EntityKey找到實(shí)體 12 var objResult = context.GetObjectByKey(entityKey); 13 //若實(shí)體存在則刪除實(shí)體 14 if (objResult != null) 15 context.DeleteObject(objResult); 16 changedCount = context.SaveChanges(); 17 if (changedCount > 0) 18 context.AcceptAllChanges(); 19 } 20 } 21 catch (Exception ex) 22 { ...... } 23 return changedCount; 24 }
ObjectContext.DeleteObject(object entity)與ObjectContext.AddObject(entitySetName string,object entity)相同,可以通過(guò)導(dǎo)航屬性,一次性刪除多個(gè)關(guān)聯(lián)實(shí)體。但如果數(shù)據(jù)庫(kù)中存在下面的數(shù)據(jù)
Company表:

Position表:

此時(shí)使用此 int Delete<Company>(2) 方法刪除Company對(duì)象,系統(tǒng)將會(huì)報(bào)錯(cuò)。這是由于導(dǎo)航屬性在默認(rèn)情況下具有延時(shí)加載的特性,在系統(tǒng)使用ObjectContext.GetObjectByKey(entityKey)方法加載實(shí)體時(shí),它的導(dǎo)航屬性不會(huì)馬上加載到上下文當(dāng)中。而是在調(diào)用該導(dǎo)航屬性時(shí),對(duì)象才會(huì)被加載。
因而系統(tǒng)通過(guò)ObjectContext.GetObjectByKey(2)獲取Company對(duì)象時(shí),對(duì)應(yīng)的Position對(duì)象并未被加載到上下文當(dāng)中,所以當(dāng)刪除Company對(duì)象時(shí),Position對(duì)象不能被同步刪除,因而造成邏輯上的錯(cuò)誤。為解決這一問(wèn)題,可以利用RelatedEnd.Load()方法提前加載導(dǎo)航屬性。
RelatedEnd是EntityCollection<TEntity> 、EntityReference的父類,它們是特定實(shí)體類型的對(duì)象集合,該實(shí)體類型表示一對(duì)多、多對(duì)一、多對(duì)多的關(guān)系。而RelatedEnd.Load()方法,可以將一個(gè)或多個(gè)相關(guān)對(duì)象提前加載到相關(guān)實(shí)體當(dāng)中。
首先通過(guò)ObjectContext.GetObjectByKey(entityKey)方法找到Company對(duì)象,然后利用反射屬性PropertyInfo類獲取導(dǎo)航屬性Position,最后使用RelatedEnd.Load()方法,把導(dǎo)航屬性加載到當(dāng)前上下文中。此時(shí)使用Delete<Company,Position>(2)方法刪除Company對(duì)象時(shí),系統(tǒng)將能正常運(yùn)行,并把對(duì)應(yīng)的Position對(duì)象一并刪除。
1 public int Delete<PKEntity, FKEntity>(int id) 2 where PKEntity : EntityObject 3 where FKEntity : EntityObject 4 { 5 int changedCount = 0; 6 try 7 { 8 using (BasicArchitectureEntities context = new BasicArchitectureEntities()) 9 { 10 //根據(jù)軟件Id建立EntityKey對(duì)象 11 EntityKey entityKey = new EntityKey( 12 "BasicArchitectureEntities." + typeof(PKEntity).Name, "Id", id); 13 //根據(jù)EntityKey查找對(duì)應(yīng)對(duì)象 14 PKEntity objResult = context.GetObjectByKey(entityKey) as PKEntity; 15 //根據(jù)FKEntity加載導(dǎo)航屬性 16 PropertyInfo propertyInfo = typeof(PKEntity).GetProperty( 17 typeof(FKEntity).Name); 18 EntityCollection<FKEntity> FKEntityList = propertyInfo.GetValue( 19 objResult, null) as EntityCollection<FKEntity>; 20 21 if (FKEntityList != null) 22 FKEntityList.Load(); 23 24 if (objResult != null) 25 context.DeleteObject(objResult); 26 changedCount = context.SaveChanges(); 27 28 if (changedCount > 0) 29 context.AcceptAllChanges(); 30 } 31 } 32 catch (Exception ex) 33 { ........ } 34 return changedCount; 35 }
通過(guò)下面的方法也可根據(jù)輸入的委托predicate,批量刪除有關(guān)的數(shù)據(jù)。
1 public int Delete<T>(Func<T,bool> predicate) where T: EntityObject 2 { 3 int changedCount = 0; 4 try 5 { 6 using (BasicArchitectureEntities context = new BasicArchitectureEntities()) 7 { 8 //根據(jù)輸入的委托查找數(shù)據(jù) 9 var list = context.CreateObjectSet<T>().Where(predicate); 10 //若存在數(shù)據(jù),刪除有關(guān)數(shù)據(jù) 11 if (list.Count() > 0) 12 foreach (var obj in list) 13 context.DeleteObject(obj); 14 15 changedCount = context.SaveChanges(); 16 if (changedCount > 0) 17 context.AcceptAllChanges(); 18 } 19 } 20 catch (Exception ex) 21 { ...... } 22 return changedCount; 23 }
與前面的例子相同,當(dāng)使用 Delete<Company>(x=>x.Id==2) 方法刪除 Company 對(duì)象時(shí),由于導(dǎo)航屬性 Position 處于延遲加載的狀態(tài),以致系統(tǒng)無(wú)法實(shí)現(xiàn)同步刪除,從而令數(shù)據(jù)出現(xiàn)邏輯性的錯(cuò)誤。
此時(shí)使用類似的方法,利用 RelatedEnd.Load() 把導(dǎo)航屬性提前加入到上下文中,再刪除Company對(duì)象時(shí),系統(tǒng)就可以把對(duì)應(yīng) Position 對(duì)象一并刪除。
1 public int Delete<PKEntity, FKEntity>(Func<PKEntity,bool> predicate) 2 where PKEntity : EntityObject 3 where FKEntity : EntityObject 4 { 5 int changedCount = 0; 6 try 7 { 8 using (BasicArchitectureEntities context = new BasicArchitectureEntities()) 9 { 10 //根據(jù)輸入的委托查找數(shù)據(jù) 11 var list = context.CreateObjectSet<PKEntity>().Where(predicate); 12 //若數(shù)目大于0,刪除有關(guān)數(shù)據(jù) 13 if (list.Count() > 0) 14 { 15 foreach (var obj in list) 16 { 17 //在刪除前加載其導(dǎo)航屬性 18 PropertyInfo propertyInfo = typeof(PKEntity) 19 .GetProperty(typeof(FKEntity).Name); 20 EntityCollection<FKEntity> FKEntityList = propertyInfo 21 .GetValue(obj, null) as EntityCollection<FKEntity>; 22 if (FKEntityList.Count > 0) 23 FKEntityList.Load(); 24 25 context.DeleteObject(obj); 26 } 27 } 28 changedCount = context.SaveChanges(); 29 30 if (changedCount > 0) 31 context.AcceptAllChanges(); 32 } 33 } 34 catch (Exception ex) 35 { ....... } 36 return changedCount; 37 }
此時(shí)使用Delete<Company,Position>(x=>x.Id==2),這樣就可以把Company對(duì)象和相關(guān)的Position對(duì)象同時(shí)刪除。
3. Update
ObjectContext 中存在方法 ObjectContext.ApplyCurrentValues<TEntity> 和 ObjectContext.ApplyOriginalValues<TEntity>,用于把將標(biāo)量值從實(shí)體復(fù)制到 ObjectContext 中具有相同主鍵的對(duì)象集中。
注意:在調(diào)用此方法前必須把實(shí)體預(yù)先加載到當(dāng)前上下文當(dāng)中,要不然系統(tǒng)將會(huì)顯示 “objectstatemanager 無(wú)法跟蹤具有相同鍵的多個(gè)對(duì)象” 的錯(cuò)誤。
由于DAL層的對(duì)象大部分使用單體模式進(jìn)行開(kāi)發(fā),而B(niǎo)aseCommand是一個(gè)共用對(duì)象,在共同操作時(shí),Create、Delete、Read 等操作一般不會(huì)對(duì)實(shí)體造成邏輯性的影響。但如果有多個(gè)實(shí)體同時(shí)調(diào)用 Update 操作,就有可能對(duì)實(shí)體造成邏輯性影響。為了避免這一事件的發(fā)生,此處使用方法鎖定的模式,以 lock(object) 鎖定某一對(duì)象,以確保在同一時(shí)間內(nèi)只會(huì)對(duì)一個(gè)實(shí)體進(jìn)行更新。
首先通過(guò)反射方式獲取對(duì)象的Id,然后通過(guò) ObjectContext.GetObjectByKey(entityKey) 方法把實(shí)體加載到當(dāng)前上下文當(dāng)中,最后利用 ObjectContext.ApplyCurrentValues<TEntity> 方法,把新加入的實(shí)體的屬性復(fù)制當(dāng)前上下文。
1 public class BaseCommand 2 { 3 private object o = new object(); 4 5 public int Update<T>(T entity) where T : EntityObject 6 { 7 lock (o) 8 { 9 int changedCount = 0; 10 Type type = typeof(T); 11 12 try 13 { 14 using (BasicArchitectureEntities context = new BasicArchitectureEntities()) 15 { 16 //獲取實(shí)體的Id屬性 17 PropertyInfo property = type.GetProperty("Id"); 18 object id = property.GetValue(entity, null); 19 //根據(jù)Id獲取上下文中的對(duì)應(yīng)實(shí)體 20 EntityKey entityKey = new EntityKey("BasicArchitectureEntities." 21 + type.Name, "Id", id); 22 var objResult = context.GetObjectByKey(entityKey); 23 //更新實(shí)體屬性 24 if (objResult != null) 25 context.ApplyCurrentValues<T>(type.Name, entity); 26 27 changedCount = context.SaveChanges(); 28 if (changedCount > 0) 29 context.AcceptAllChanges(); 30 } 31 } 32 catch (Exception ex) 33 { ... } 34 return changedCount; 35 } 36 } 37 }
在一對(duì)多,多對(duì)一關(guān)系時(shí),也可以使用以下方法進(jìn)行導(dǎo)航屬性的同步更新。首先通過(guò)反射獲取主實(shí)體的主鍵Id,然后建立EntityKey對(duì)象,再通過(guò)ObjectContext.GetObjectByKey(entityKey)方法在當(dāng)前上下文當(dāng)中獲取此實(shí)體,最后通過(guò) ObjectContext.ApplyCurrentValues<TEntity> 方法,把新加入的實(shí)體的屬性復(fù)制當(dāng)前上下文。
下一步就是對(duì)導(dǎo)航屬性進(jìn)行更新,首先通過(guò)反射獲取外鍵屬性,然后對(duì)一對(duì)多,多對(duì)一的關(guān)系進(jìn)行分別處理。在一對(duì)多關(guān)系時(shí),把導(dǎo)航屬性轉(zhuǎn)換成EntityCollection<T2>對(duì)象集合,然后通過(guò) ObjectContext.ApplyCurrentValues<TEntity> 方法對(duì)集合中的每個(gè)對(duì)象進(jìn)行逐個(gè)更新。
在多對(duì)一關(guān)系時(shí),直接把導(dǎo)航屬性轉(zhuǎn)換成T2類型的對(duì)象進(jìn)行更新。
1 public int Update<T1, T2>(T1 entity) 2 where T1 : EntityObject 3 where T2 : EntityObject 4 { 5 lock (o) 6 { 7 int changedCount = 0; 8 Type typeT1 = typeof(T1); 9 Type typeT2 = typeof(T2); 10 try 11 { 12 using (BasicArchitectureEntities context = new BasicArchitectureEntities()) 13 { 14 PropertyInfo property = typeT1.GetProperty("Id"); 15 object id = property.GetValue(entity, null); 16 17 //根據(jù)軟件Id建立EntityKey對(duì)象 18 EntityKey entityKey = new EntityKey("BasicArchitectureEntities." 19 + typeT1.Name, "Id", id); 20 //根據(jù)EntityKey查找對(duì)應(yīng)對(duì)象 21 T1 objT1 = context.GetObjectByKey(entityKey) as T1; 22 //在上下文中更新當(dāng)前對(duì)象 23 if (objT1 != null) 24 context.ApplyCurrentValues<T1>(typeT1.Name, entity); 25 26 //獲取外鍵屬性 27 PropertyInfo propertyInfo = typeT1.GetProperty(typeT2.Name); 28 29 //在一對(duì)多關(guān)鍵時(shí)更新導(dǎo)航屬性 30 var T2List = propertyInfo.GetValue(entity, null) 31 as EntityCollection<T2>; 32 if (T2List != null) 33 { 34 foreach (var obj in T2List.ToList()) 35 { 36 var oldEntity = context.GetObjectByKey(obj.EntityKey); 37 if (oldEntity != null) 38 context.ApplyCurrentValues<T2>(typeT2.Name, obj); 39 } 40 } 41 42 //在多對(duì)一,一對(duì)一關(guān)系時(shí)更新導(dǎo)航屬性 43 var objT2 = propertyInfo.GetValue(entity, null) as T2; 44 if (objT2!= null) 45 { 46 var oldEntity = context.GetObjectByKey(objT2.EntityKey); 47 if (oldEntity != null) 48 context.ApplyCurrentValues<T2>(typeT2.Name, objT2); 49 } 50 51 changedCount = context.SaveChanges(); 52 if (changedCount > 0) 53 context.AcceptAllChanges(); 54 } 55 catch (Exception ex) 56 { ...... } 57 return changedCount; 58 } 59 }
通過(guò)此方法,無(wú)論你要通過(guò)Company同步更新Position,還是反過(guò)來(lái)通過(guò)Position同步更新Company,系統(tǒng)也能正常運(yùn)行。
4. Read
Read 是CRUD中最常見(jiàn)的,下面就為大家介紹最通用的幾種方法
4.1 通過(guò)Id獲取單個(gè)實(shí)體
1 public T GetObject<T>(int id) where T : EntityObject 2 { 3 try 4 { 5 using (BasicArchitectureEntities context = new BasicArchitectureEntities()) 6 { 7 EntityKey entityKey = new EntityKey("BasicArchitectureEntities." 8 + typeof(T).Name, "Id", id); 9 var objResult = context.GetObjectByKey(entityKey); 10 return objResult as T; 11 } 12 } 13 catch (Exception ex) 14 { 15 return null; 16 } 17 }
4.2 通過(guò)輸入的Func<T,bool>委托獲取對(duì)象
1 public T GetObject<T>(Func<T,bool> predicate) where T : EntityObject 2 { 3 try 4 { 5 using (BasicArchitectureEntities context = new BasicArchitectureEntities()) 6 { 7 var objectSet = context.CreateObjectSet<T>().Where(predicate); 8 if (objectSet.Count() > 0) 9 return objectSet.First(); 10 else 11 return null; 12 } 13 } 14 catch (Exception ex) 15 { 16 return null; 17 } 18 }
4.3通過(guò)輸入的Func<T,bool>委托獲取對(duì)象,并同時(shí)加載單個(gè)導(dǎo)航屬性
1 public T GetObject<T>(Func<T, bool> predicate,string includePath) 2 where T : EntityObject 3 { 4 try 5 { 6 using (BasicArchitectureEntities context = new BasicArchitectureEntities()) 7 { 8 var objectQuery = context.CreateObjectSet<T>() 9 .Include(includePath) 10 .Where(predicate); 11 12 if (objectQuery.Count() > 0) 13 return objectQuery.First(); 14 else 15 return null; 16 } 17 } 18 catch (Exception ex) 19 { 20 return null; 21 } 22 }
4.4通過(guò)輸入的Func<T,bool>委托獲取對(duì)象,并同時(shí)加載多個(gè)導(dǎo)航屬性
1 public T GetObject<T>(Func<T, bool> predicate, string[] includePath) 2 where T : EntityObject 3 { 4 try 5 { 6 using (BasicArchitectureEntities context = new BasicArchitectureEntities()) 7 { 8 var list = context.CreateObjectSet<T>().Where("1==1"); 9 10 foreach (var path in includePath) 11 list=list.Include(path); 12 13 var returnValue = list.Where(predicate).ToList(); 14 15 if (returnValue.Count() > 0) 16 return returnValue.First(); 17 else 18 return null; 19 } 20 } 21 catch (Exception ex) 22 { 23 return null; 24 } 25 }
4.5 通過(guò)輸入的Func<T,bool>委托獲取對(duì)象集合
1 public IList<T> GetList<T>(Func<T,bool> func) where T:EntityObject 2 { 3 try 4 { 5 using (BasicArchitectureEntities context = new BasicArchitectureEntities()) 6 { 7 ObjectSet<T> objectSet = context.CreateObjectSet<T>(); 8 IList<T> list = objectSet.Where(func).ToList(); 9 return list; 10 } 11 } 12 catch (Exception ex) 13 { 14 return null; 15 } 16 }
4.6通過(guò)輸入的Func<T,bool>委托獲取對(duì)象集合,并同時(shí)加入單個(gè)導(dǎo)航屬性
1 public IList<T> GetList<T>(Func<T, bool> func,string includePath) 2 where T : EntityObject 3 { 4 try 5 { 6 using (BasicArchitectureEntities context = new BasicArchitectureEntities()) 7 { 8 ObjectSet<T> objectSet = context.CreateObjectSet<T>(); 9 IList<T> list = objectSet.Include(includePath).Where(func).ToList(); 10 return list; 11 } 12 } 13 catch (Exception ex) 14 { 15 return null; 16 } 17 }
4.7通過(guò)輸入的Func<T,bool>委托獲取對(duì)象集合,并同時(shí)加入多個(gè)導(dǎo)航屬性
1 public IList<T> GetList<T>(Func<T, bool> func, string[] includePath) 2 where T : EntityObject 3 { 4 try 5 { 6 using (BasicArchitectureEntities context = new BasicArchitectureEntities()) 7 { 8 var list = context.CreateObjectSet<T>().Where("1==1"); 9 foreach (var path in includePath) 10 list = list.Include(path); 11 return list.Where(func).ToList(); 12 } 13 } 14 catch (Exception ex) 15 { 16 return null; 17 } 18 }
4.8 通過(guò)原始的SqlCommandText獲取對(duì)象集
1 public IList<T> GetList<T>(string commandText) 2 { 3 try 4 { 5 using (BasicArchitectureEntities context = new BasicArchitectureEntities()) 6 { 7 IList<T> list = context.ExecuteStoreQuery<T>(commandText).ToList(); 8 return list; 9 } 10 } 11 catch (Exception ex) 12 { 13 return null; 14 } 15 }
只能完成這一個(gè)DAL層的通用類以后,您就可在CompanyDAL、PersonDAL、PositionDAL ...... 等多個(gè)類中調(diào)用這個(gè)通用類,輕松地完成各項(xiàng)CRUD的操作。
1 public class CompanyDAL:ICompanyDAL 2 { 3 private BaseCommand command = new BaseCommand(); 4 5 public int AddCompany(Company company) 6 { 7 return command.Add<Company>(company); 8 } 9 10 public int DeleteCompany(int id) 11 { 12 return command.Delete<Company>(id); 13 } 14 15 public int UpdateComapny(Company company) 16 { 17 return command.Update<Company>(company); 18 } 19 ............. 20 }
相比起以往的SqlCommand操作,Entity Framework更體現(xiàn)出映射的靈活性。以往的操作中,即使開(kāi)發(fā)出一個(gè)通用類,CommandText 通常都需要使用手工輸入,特別是重復(fù)的Update命令操作中,往往令人不厭其煩。通過(guò)Entity Framework可以把CRUD更高度地集中在一個(gè)通用類,令開(kāi)發(fā)變得更加簡(jiǎn)單。
希望本篇文章對(duì)您的系統(tǒng)開(kāi)發(fā)有所幫助。
對(duì)軟件架構(gòu)開(kāi)發(fā)有興趣的朋友歡迎加入博客園討論組 “.NET高級(jí)編程”
對(duì) .NET 開(kāi)發(fā)有興趣的朋友歡迎加入QQ群:162338858 共同探討 !
作者:風(fēng)塵浪子
http://www.rzrgm.cn/leslies2/archive/2012/05/16/2504673.html
原創(chuàng)作品,轉(zhuǎn)載時(shí)請(qǐng)注明作者及出處
posted on 2012-05-17 14:16 風(fēng)塵浪子 閱讀(14511) 評(píng)論(18) 收藏 舉報(bào)
本文將為您介紹一個(gè)對(duì)應(yīng)Entity Framework的 CRUD 通用類,相比起以往的SqlCommand操作,Entity Framework更體現(xiàn)出映射的靈活性。以往的操作中,即使開(kāi)發(fā)出一個(gè)通用類,CommandText 通常都需要使用手工輸入,特別是重復(fù)的Update命令操作中,往往令人不厭其煩。通過(guò)Entity Framework可以把CRUD更高度地集中在一個(gè)通用類,令開(kāi)發(fā)變得更加簡(jiǎn)單。
浙公網(wǎng)安備 33010602011771號(hào)