Fastest way to map result of SqlDataReader to object

后端 未结 11 1079
花落未央
花落未央 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 08:57

    I took both pimbrouwers and HouseCat's answers and come up with me. In my scenario, the column name in database has snake case format.

    public static T ConvertToObject(string query) where T : class, new()
        {
            using (var conn = new SqlConnection(AutoConfig.ConnectionString))
            {
                conn.Open();
                var cmd = new SqlCommand(query) {Connection = conn};
                var rd = cmd.ExecuteReader();
                var mappedObject = new T();
    
                if (!rd.HasRows) return mappedObject;
                var accessor = TypeAccessor.Create(typeof(T));
                var members = accessor.GetMembers();
                if (!rd.Read()) return mappedObject;
                for (var i = 0; i < rd.FieldCount; i++)
                {
                    var columnNameFromDataTable = rd.GetName(i);
                    var columnValueFromDataTable = rd.GetValue(i);
    
                    var splits = columnNameFromDataTable.Split('_');
                    var columnName = new StringBuilder("");
                    foreach (var split in splits)
                    {
                        columnName.Append(CultureInfo.InvariantCulture.TextInfo.ToTitleCase(split.ToLower()));
                    }
    
                    var mappedColumnName = members.FirstOrDefault(x =>
                        string.Equals(x.Name, columnName.ToString(), StringComparison.OrdinalIgnoreCase));
    
                    if(mappedColumnName == null) continue;
                    var columnType = mappedColumnName.Type;
    
                    if (columnValueFromDataTable != DBNull.Value)
                    {
                        accessor[mappedObject, columnName.ToString()] = Convert.ChangeType(columnValueFromDataTable, columnType);
                    }
                }
    
                return mappedObject;
            }
        }
    

提交回复
热议问题