zoukankan      html  css  js  c++  java
  • 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叫容器名和一个字典串组成

    回到目录

  • 相关阅读:
    lua 5.3最简单plugin编写
    CMake for MFC example
    写了个自动生成vcxproj的程序
    kindle試玩
    解放双手:如何在本地调试远程服务器上的Node代码
    PM2实用入门指南
    Express使用手记:核心入门
    Node服务一键离线部署
    fis-receiver:一行命令将项目部署到远程服务器
    Reflux系列01:异步操作经验小结
  • 原文地址:https://www.cnblogs.com/lori/p/2747152.html
Copyright © 2011-2022 走看看