Fastest way to map result of SqlDataReader to object

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

    Perhaps the approach I will present isn't the most efficient but gets the job done with very little coding effort. The main benefit I see here is that you don't have to deal with data structure other than building a compatible (mapable) object.

    If you convert the SqlDataReader to DataTable then serialize it using JsonConvert.SerializeObject you can then deserialize it to a known object type using JsonConvert.DeserializeObject

    Here is an example of implementation:

            SqlDataReader reader = null;
            SqlConnection myConnection = new SqlConnection();
            myConnection.ConnectionString = ConfigurationManager.ConnectionStrings["DatabaseConnection"].ConnectionString;
            SqlCommand sqlCmd = new SqlCommand();
            sqlCmd.CommandType = CommandType.Text;
            sqlCmd.CommandText = "SELECT * FROM MyTable";
            sqlCmd.Connection = myConnection;
            myConnection.Open();
            reader = sqlCmd.ExecuteReader();
    
            var dataTable = new DataTable();
            dataTable.Load(reader);
    
            List myObjects = new List();
    
            if (dataTable.Rows.Count > 0)
            {
                var serializedMyObjects = JsonConvert.SerializeObject(dataTable);
                // Here you get the object
                myObjects = (List)JsonConvert.DeserializeObject(serializedMyObjects, typeof(List));
            }
    
            myConnection.Close();
    

提交回复
热议问题