现在的位置: 首页 > 综合 > 正文

使用反射解决实体类型转换问题 by hyw

2012年01月27日 ⁄ 综合 ⁄ 共 3545字 ⁄ 字号 评论关闭
     我在做一个以Northwind为数据库,使用EDM、ASP.NET MVC1.0框架的示例项目。项目刚刚开始,目前在做一些技术测试。当对实体层进行操作时,问题来了。

      问题:对对象集进行查询的时候,我们往往不需要查询所有的字段,但返回的时候却要返回这个对象或对象结合。这是我们该如何做?

      例如:Categories这个表(在EDM中为Category类)中包含了Picture这个字段,Picture是存放图片的,数据相对比较大,那我们在读取这个表的时候每次都全部取出数据势必不是一个高效的做法。

      解决过程:

      首先,我们在需要查询特定字段的时候使用  Entity SQL来进行操作。

      例如我们只要查询Category的CategoryID,CategoryName字段

      那么我们可以这样做:

      string esqlCommand= "SELECT c.CategoryID,c.CategoryName FROM NorthwindEntities.Category AS c";

      using (NorthwindEntities northwind = new NorthwindEntities())
      {
                List<Object> readers = northwind.CreateQuery<Object>(esqlCommand).ToList(); 

                //List<Obect> readers = (from c in northwind.Category select new { CategoryID = c.CategoryID,CategoryName = c.CategoryName).ToList();第二种方法

                //这里无法使用northwind.CreateQuery<Category>,因为执行完上面的esqlCommand后返回的是匿名类型,它无法如此转换成Entity类型

                //这就是问题关键。

      }

      第一次想到的方法是

      class MyCategory:Category{}//MyCategory类继承Category类也就继承了它的属性,这样我就可以使结果返回MyCategory

      string esqlCommand= "SELECT c.CategoryID,c.CategoryName FROM NorthwindEntities.Category AS c";

      using (NorthwindEntities northwind = new NorthwindEntities())
      {
               
List<MyCategory> readers = (from c in northwind.Category select new MyCategory { CategoryID = c.CategoryID,CategoryName = c.CategoryName).ToList();

                //这里无法使用northwind.CreateQuery<Category>,因为执行完上面的esqlCommand后返回的是匿名类型,它无法如此转换成Entity类型

                //这就是问题关键。

      }

      OK,但是以后每个类你都要增加各MyClass,而且这个类也使实体层显得不“干净”。这时候想到了使用反射来对把结果转换成我们要的实体,上网看了dudu的CN.Text开发笔记—利用反射将数据读入实体类。以下是在dudu基础上写的方法。

 

public class Shared
    {
        private static void ReaderToEntity(IDataRecord reader, Object entity)
        {
            for (int i = 0; i < reader.FieldCount; i++)
            {
                System.Reflection.PropertyInfo propertyInfo = entity.GetType().GetProperty(reader.GetName(i));
                if (propertyInfo != null)
                {
                    if (reader.GetValue(i) != DBNull.Value)
                    {
                        propertyInfo.SetValue(entity, reader.GetValue(i), null);
                    }
                }
            }
        }

        public static T ExecToEntity<T>(string esqlCommand)
        {
            DbDataRecord reader;
            using (NorthwindEntities northwind = new NorthwindEntities())
            {
                reader = northwind.CreateQuery<DbDataRecord>(esqlCommand).FirstOrDefault();
            }
            if (reader == null)
            {
                return default(T);
            }
            else
            {
                T entity = (T)Activator.CreateInstance(typeof(T));
                ReaderToEntity(reader, entity);
                return entity;
            }
        }

        public static List<T> ExecToEntities<T>(string esqlCommand)
        {
            List<T> entities = new List<T>();
            using (NorthwindEntities northwind = new NorthwindEntities())
            {
                List<DbDataRecord> readers = northwind.CreateQuery<DbDataRecord>(esqlCommand).ToList();

                foreach (DbDataRecord reader in readers)
                {
                    T entity = (T)Activator.CreateInstance(typeof(T));
                    ReaderToEntity(reader, entity);
                    entities.Add(entity);
                }
            }
            return entities;
        }

}

      现在我们在操作时就简单多了

 

        public static List<Category> List()
        {
            string cmd = "SELECT c.CategoryID,c.CategoryName FROM NorthwindEntities.Category AS c";

            return Shared.ExecToEntities<Category>(cmd);
        }

总结:问题的解决方法使用了反射机制,而反射对效率还是有一定影响的,所以尽量在读取数据时减少读取的数量。比如页面呈现多少条数据你就查询多少条,不要一下全部读出来再进行分页。

如果你要查询表中所有字段的话,你就不必使用该方法了,直接用常规方法吧。

抱歉!评论已关闭.