Fastest way to map result of SqlDataReader to object

后端 未结 11 1093
花落未央
花落未央 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:52

    When in doubt regarding anything db or reflection, I ask myself, "what would Marc Gravell do?".

    In this case, he would use FastMember! And you should too. It's the underpinning to the data conversions in Dapper, and can easily be used to map your own DataReader to an object (should you not want to use Dapper).

    Below is an extension method converting a SqlDataReader into something of type T:

    PLEASE NOTE: This code implies a dependency on FastMember and is written for .NET Core (though could easily be converted to .NET Framework/Standard compliant code).

    public static T ConvertToObject(this SqlDataReader rd) where T : class, new()
    {
        Type type = typeof(T);
        var accessor = TypeAccessor.Create(type);
        var members = accessor.GetMembers();
        var t = new T();
    
        for (int i = 0; i < rd.FieldCount; i++)
        {
            if (!rd.IsDBNull(i))
            {
                string fieldName = rd.GetName(i);
    
                if (members.Any(m => string.Equals(m.Name, fieldName, StringComparison.OrdinalIgnoreCase)))
                {
                    accessor[t, fieldName] = rd.GetValue(i);
                }
            }
        }
    
        return t;
    }
    

提交回复
热议问题