Fastest way to map result of SqlDataReader to object

后端 未结 11 1097
花落未央
花落未央 2021-02-04 08:49

I\'m comparing materialize time between Dapper and ADO.NET and Dapper. Ultimately, Dapper tend to faster than ADO.NET, though the first time a given fetch query was executed

11条回答
  •  故里飘歌
    2021-02-04 09:01

    This kinda works

     public static object PopulateClass(object o, SQLiteDataReader dr, Type T)
        {
            Type type = o.GetType();
            PropertyInfo[] properties = type.GetProperties();
    
            foreach (PropertyInfo property in properties)
            {
                T.GetProperty(property.Name).SetValue(o, dr[property.Name],null);
            }
            return o;
        }
    

    Note I'm using SQlite here but the concept is the same. As an example I'm filling a Game object by calling the above like this-

    g = PopulateClass(g, dr, typeof(Game)) as Game;
    

    Note you have to have your class match up with datareader 100%, so adjust your query to suit or pass in some sort of list to skip fields. With a SQLDataReader talking to a SQL Server DB you have a pretty good type match between .net and the database. With SQLite you have to declare your ints in your class as Int64s for this to work and watch sending nulls to strings. But the above concept seems to work so it should get you going. I think this is what the Op was after.

提交回复
热议问题