像 DataAdapter 这样的 Dapper 命令

Dapper command like DataAdapter

拜托,我可以将此方法转换为使用 Dapper 吗?


public DataTable GetLeituras ( int ultimas )
    {
        DataTable listaLeiturasRomaneio = new DataTable();
        try
        {
            _sqlConnection.Open();

            _sqlCommand = new SqlCommand();
            _sqlCommand.Connection = _sqlConnection;
            _sqlCommand.CommandText = "BuscarUltimasLeituras";
            _sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
            _sqlCommand.Parameters.Add("@Last", SqlDbType.Int).Value = ultimas;
            _sqlAdapter = new SqlDataAdapter(_sqlCommand);
            _sqlAdapter.Fill(listaLeiturasRomaneio);
        }
        catch ( SqlException )
        {
            listaLeiturasRomaneio = null;
        }
        finally
        {
            _sqlConnection.Close();
        }
        return listaLeiturasRomaneio;
    }

如果你还想要DataTable,你可以试试:

var listaLeiturasRomaneio = new DataTable();
using (var reader = _sqlConnection.ExecuteReader(
    "BuscarUltimasLeituras", new { Last = ultimas },
    commandType: CommandType.StoredProcedure))
{
    listaLeiturasRomaneio.Load(reader);
}

但是,更典型的用法是创建一个 class 来匹配您的数据,然后:

var listaLeiturasRomaneio = _sqlConnection.Query<YourType>(
    "BuscarUltimasLeituras", new { Last = ultimas },
    commandType: CommandType.StoredProcedure).AsList();

请注意,dapper 也支持 dynamic 用法,但这通常是为了随意使用:

var listaLeiturasRomaneio = _sqlConnection.Query(
    "BuscarUltimasLeituras", new { Last = ultimas },
    commandType: CommandType.StoredProcedure).AsList();