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 @ 2012-10-30 22:24  张占岭  阅读(5208)  评论(1编辑  收藏  举报