EF架構~為ObjectContext類型加個Find方法


回到目錄

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叫容器名和一個字典串組成

回到目錄


免責聲明!

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



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