Convert SQL Query to IList using of Dapper

c#-4.0 dapper sql sql-server visual-studio-2012

Question

I use VS2012 and SQL Server 2012

I add Dapper to my VS2012 like this

enter image description here

I have one class like this :

    public class DomainClass
    {
        public SexEnum sex { get; set; }
        public int Id { get; set; }
        public string Name { get; set; }
    }

    enum SexEnum
    {
        Men = 0, Women = 1
    }

I have a table ATest and i have a query like this :

Select * From ATest

How i can execute this query and convert my result in to IList of DomainClass with Dapper ?

Accepted Answer

public static IList<DomainClass> GetAllDomains()
{
    using (var con = new SqlConnection(Properties.Settings.Default.YourConnection))
    {
        const String sql = "Select sex, Id, Name  From ATest ORDER BY Name ASC;";
        con.Open();
        IList<DomainClass> domains = con.Query<DomainClass>(sql).ToList();
        return domains;
    }
}

Popular Answer

I write this static class and this extension method :

/// <summary>
/// Put this Class in your project 
/// and use ConvertSqlQueryToIList extension method on SqlConnection object.
/// </summary>
public static class Convert
{

    public static IList<T> ConvertSqlQueryToIList<T>(
                                           this SqlConnection sqlConn, 
                                           T domainClass, 
                                           string sqlQueryCommand
                                                            )
    {
        ConnectionState connectionState = ConnectionState.Closed;
        try
        {

            if (sqlConn.State != ConnectionState.Open)
            {
                sqlConn.Open();
                connectionState = sqlConn.State;
            }

            IList<T> result = sqlConn.Query<T>(sqlQueryCommand).ToList();

            return result;
        }
        catch (Exception exception)
        {

            throw exception;
        }
        finally
        {
            if (connectionState == ConnectionState.Closed)
                sqlConn.Close();
        }
    }

}

And i fond that Dapper convert int field in to Enum property,

like Sex property in my quetsion.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why