user2688063
user2688063

Reputation: 313

Does dapper support .net dataset

in my opinion for dapper.query object there is a datareader, for dapper.Execute there is a ExectureNonQuery object. Correct me if i am wrong .

Can we use dapper for dataset which returns multiple tables?

Upvotes: 11

Views: 19151

Answers (2)

Rahul Sharma
Rahul Sharma

Reputation: 8312

I might be late here but this is how I am doing the conversion of the IDataReader to a DataSet. Dapper returns a IDataReader when we use the ExecuteReaderAsync method. More information on this addition can be found here and here.

This is my attempt on this:

public async Task<DataSet> GetUserInformationOnUserId(int UserId)
{
    var storedprocedure = "usp_getUserInformation";
    var param = new DynamicParameters();
    param.Add("@userId", UserId);
    var list = await SqlMapper.ExecuteReaderAsync(_connectionFactory.GetEpaperDBConnection, storedprocedure, param, commandType: CommandType.StoredProcedure);
    var dataset = ConvertDataReaderToDataSet(list);
    return dataset;
}

And the ConvertDataReaderToDataSet will take in the IDataReader, you can use this method to convert the IReader to Dataset:

public DataSet ConvertDataReaderToDataSet(IDataReader data)
{
    DataSet ds = new DataSet();
    int i = 0;
    while (!data.IsClosed)
    {
        ds.Tables.Add("Table" + (i + 1));
        ds.EnforceConstraints = false;
        ds.Tables[i].Load(data);
        i++;
    }                    
    return ds;
}

Upvotes: 14

Marc Gravell
Marc Gravell

Reputation: 1062975

No, there is not any built in support for DataSet, primarily because it seems largely redundant, but also because that isn't what dapper targets. But that doesn't mean it doesn't include an API for handling a query that selects multiple results; see QueryMultiple:

using (var multi = conn.QueryMultiple(sql, args))
{
    var ids = multi.Read<int>().ToList();
    var customers = multi.Read<Customer>().ToList();
    dynamic someOtherRow = multi.Read().Single();
    int qty = someOtherRow.Quantity, price = someOtherRow.Price;
}

Note that this API is forwards only (due to the nature of IDataReader etc) - basically, each Read / Read<T> etc maps to the next result grid in turn.

Upvotes: 12

Related Questions