Fastest way to map result of SqlDataReader to object

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

    Here's a way to make your ADO.NET code faster.

    When you do your select, list out the fields that you are selecting rather than using select *. This will let you ensure the order that the fields are coming back even if that order changes in the database.Then when getting those fields from the Reader, get them by index rather than by name. Using and index is faster.

    Also, I'd recommend not making string database fields nullable unless there is a strong business reason. Then just store a blank string in the database if there is no value. Finally I'd recommend using the Get methods on the DataReader to get your fields in the type they are so that casting isn't needed in your code. So for example instead of casting the DataReader[index++] value as an int use DataReader.GetInt(index++)

    So for example, this code:

     salesOrderHeader = new SalesOrderHeaderSQLserver();
     salesOrderHeader.SalesOrderId = (int)reader["SalesOrderId"];
     salesOrderHeader.SalesOrderNumber =       reader["SalesOrderNumber"] as string;
     salesOrderHeader.AccountNumber = reader["AccountNumber"] as string;
    

    becomes

     int index = 0;
     salesOrderHeader = new SalesOrderHeaderSQLserver();
     salesOrderHeader.SalesOrderId = reader.GetInt(index++);
     salesOrderHeader.SalesOrderNumber = reader.GetString(index++);
     salesOrderHeader.AccountNumber = reader.GetString(index++);
    

    Give that a whirl and see how it does for you.

提交回复
热议问题