C# - IDataReader to Object mapping using generics

后端 未结 10 723
情歌与酒
情歌与酒 2020-12-16 19:07

How can I map a DataReader object into a class object by using generics?

For example I need to do the following:

public class Mapper
    {
          


        
相关标签:
10条回答
  • 2020-12-16 19:58

    what about following

    abstract class DataMapper
    {
        abstract public object Map(IDataReader);
    }
    
    class BookMapper : DataMapper
    {
       override public object Map(IDataReader reader)
       {
           ///some mapping stuff
           return book;
       }
    }
    
    public class Mapper<T>
    {
        public static List<T> MapObject(IDataReader dr)
        {
            List<T> objects = new List<T>();
            DataMapper myMapper = getMapperFor(T);
            while (dr.Read())
            {
                objects.Add((T)myMapper(dr));
            }
    
            return objects;
        }
    
        private DataMapper getMapperFor(T myType)
        {
           //switch case or if or whatever
           ...
           if(T is Book) return bookMapper;
    
        }
    }
    

    Don't know if it is syntactically correct, but I hope u get the idea.

    0 讨论(0)
  • 2020-12-16 19:59

    You could use this LateBinder class I wrote: http://codecube.net/2008/12/new-latebinder/.

    I wrote another post with usage: http://codecube.net/2008/12/using-the-latebinder/

    0 讨论(0)
  • 2020-12-16 20:00

    This is going to be very hard to do for the reason that you are basically trying to map two unknowns together. In your generic object the type is unknown, and in your datareader the table is unknown.

    So what I would suggest is you create some kind of column attribute to attach to the properties of you entity. And then look through those property attributes and try to look up the data from those attributes in the datareader.

    Your biggest problem is going to be, what happens if one of the properties isn't found in the reader, or vice-versa, one of the columns in the reader isn't found in the entity.

    Good luck, but if you want to do something like this, you probably want a ORM or at the very least some kind of Active Record implementation.

    0 讨论(0)
  • 2020-12-16 20:01

    Have a look at http://CapriSoft.CodePlex.com

    0 讨论(0)
提交回复
热议问题