ObjectContext作為entity framework的最原始的數據上下文對象,它的操作都是具有原始性的,沒有被封閉過的,這也就難免在有些功能上欠缺一點,用過DbContext作為EF數據上下文的同學一定有留意到它的Find<TEntity>(params object[] keyValues)方法,不錯,它確實比較方便,通過主鍵(可以是復合主鍵)來查找實體,這個功能在ObjectContext對象上是沒有被提供的,所以,我把這個功能在ObjectContext上實現了一下,現在分享給各位:
1 /// <summary> 2 /// 根據主鍵得到一個實體 3 /// </summary> 4 /// <typeparam name="TEntity"></typeparam> 5 /// <param name="id"></param> 6 /// <returns></returns> 7 public virtual TEntity GetEntity<TEntity>(params object[] id) where TEntity : class 8 { 9 var count = 0; 10 List<PropertyInfo> res_Primary = new List<PropertyInfo>(); 11 List<EntityKeyMember> keyMemberList = new List<EntityKeyMember>(); 12 PropertyInfo[] properties = typeof(TEntity).GetProperties(); 13 foreach (PropertyInfo pI in properties) 14 { 15 System.Object[] attributes = pI.GetCustomAttributes(true); 16 foreach (object attribute in attributes) 17 { 18 if (attribute is EdmScalarPropertyAttribute) 19 { 20 if ((attribute as EdmScalarPropertyAttribute).EntityKeyProperty && !(attribute as EdmScalarPropertyAttribute).IsNullable) 21 keyMemberList.Add(new EntityKeyMember(pI.Name, id[count])); 22 count++; 23 } 24 25 } 26 } 27 return _db.GetObjectByKey(new EntityKey(_db.DefaultContainerName + "." + typeof(TEntity).Name, keyMemberList)) as TEntity; 28 29 }
術語說明:ObjectSet<T> 相當於是表的結果集,在DbContext環境中叫DbSet<T>
EntityContainerName:EDMX所使用的容器名稱
EntityKey:在EF中叫實體鍵,也叫主鍵,一個EntityKey叫容器名和一個字典串組成