2

我使用VS2012SQL Server 2012

我添加Dapper到我的VS2012喜欢这个

在此处输入图像描述

我有一堂这样的课:

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

    enum SexEnum
    {
        Men = 0, Women = 1
    }

我有一张桌子ATest,我有这样的查询:

Select * From ATest

我如何执行此查询并将结果转换为IList of DomainClass使用 Dapper ?

4

2 回答 2

4
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;
    }
}
于 2013-11-08T09:19:10.580 回答
1

我写了这个静态类和这个扩展方法:

/// <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();
        }
    }

}

我喜欢 Dapper 将 int 字段转换为 Enum 属性,

就像我的问题中的性财产。

于 2013-11-08T10:28:38.210 回答