中文字幕精品亚洲无线码二区,国产黄a三级三级三级看三级,亚洲七七久久桃花影院,丰满少妇被猛烈进入,国产小视频在线观看网站

EF架構~為ObjectContext類(lei)型加個Find方(fang)法

回到目錄

ObjectContext作(zuo)(zuo)為(wei)entity framework的最(zui)原(yuan)始(shi)的數據上(shang)下文(wen)對象,它的操(cao)作(zuo)(zuo)都是(shi)具有(you)(you)原(yuan)始(shi)性的,沒(mei)有(you)(you)被封(feng)閉過的,這也(ye)就(jiu)難免在有(you)(you)些功(gong)能(neng)上(shang)欠(qian)缺一點,用過DbContext作(zuo)(zuo)為(wei)EF數據上(shang)下文(wen)的同(tong)學一定有(you)(you)留(liu)意到它的Find<TEntity>(params object[] keyValues)方法,不(bu)錯,它確實比較方便,通(tong)過主鍵(可以(yi)是(shi)復合主鍵)來查(cha)找實體(ti),這個(ge)(ge)功(gong)能(neng)在ObjectContext對象上(shang)是(shi)沒(mei)有(you)(you)被提供(gong)的,所以(yi),我把這個(ge)(ge)功(gong)能(neng)在ObjectContext上(shang)實現了(le)一下,現在分享給各位(wei):

 1   /// <summary>
 2         /// 根(gen)據主鍵(jian)得到一個實體
 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> 相當于是(shi)表的結果集(ji),在DbContext環境(jing)中叫(jiao)DbSet<T>

              EntityContainerName:EDMX所使用(yong)的(de)容器名稱

              EntityKey:在EF中叫(jiao)實體鍵(jian),也叫(jiao)主鍵(jian),一個EntityKey叫(jiao)容器(qi)名和(he)一個字(zi)典串組成

回到目錄

posted @ 2012-10-30 22:24  張占嶺  閱讀(5231)  評論(1)    收藏  舉報