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

回到目录

posted @   张占岭  阅读(5217)  评论(1编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示