Dapper强类型查询返回默认对象值

时间:2016-12-14 18:27:46

标签: c# asp.net-core-mvc dapper

刚开始使用Dapper并喜欢它。 我遇到问题,它会返回正确数量的对象,但它们的属性都有默认值

using (var dbConnection = Connection)
        {
            await dbConnection.OpenAsync();

            const string sQuery2 = @"SELECT * FROM ChipTime WHERE MacAddress = @MacAddress AND ClientId = @ClientId ORDER BY CreateDate Desc";
            var chipTimes = dbConnection.Query<ChipTime>(sQuery2, new { ClientId = clientId, MacAddress = id }).ToList();
        }

chipTimes只有一个ChipTime对象列表,所有这些对象都只有默认属性,而不是数据库中的值

如果我这样做

using (var dbConnection = Connection)
        {
            await dbConnection.OpenAsync();

            const string sQuery2 =
                @"SELECT * FROM ChipTime WHERE MacAddress = @MacAddress AND ClientId = @ClientId ORDER BY CreateDate Desc";
            var chipTimes = dbConnection.Query(sQuery2, new {ClientId = clientId, MacAddress = id}).ToList();
        }

动态都在

中具有正确的值

ChipTime类非常简单

    public class ChipTime
{
    public int TimeId { get; set; }
    public string TimingPoint { get; set; }
    public string MacAddress { get; set; }
    public string ChipCode { get; set; }
    public DateTime ChipDateTime { get; set; }
    public DateTime ReaderTime { get; set; }
    public int ReaderTimeDec { get; set; }
    public string UhfReaderNo { get; set; }
    public string Rssi { get; set; }
    public DateTime CreateDate{ get; set; }
    public int ReplStatus { get; set; }
    public int RaceId { get; set; }
    public int ClientId { get; set; }
    public int RecordNo { get; set; }
    public string AntennaNo { get; set; }
    public bool IsRaceNo { get; set; }

}

我做错了什么?

2 个答案:

答案 0 :(得分:2)

尝试指定要在查询中选择的列的名称,而不是执行SELECT *:

const string sQuery2 = @"SELECT TimeId, TimingPoint, MacAddress, ChipCode, ... FROM ChipTime WHERE MacAddress = @MacAddress AND ClientId = @ClientId ORDER BY CreateDate Desc";

Why is SELECT * considered harmful?

  

我尝试了这个但结果相同。

确保ChipTime表中的列与ChipTime类的属性名称完全匹配,并指定类型参数(dbConnection.Query &lt; ChipTime&gt; ):

using (var dbConnection = Connection)
    {
        await dbConnection.OpenAsync();

        const string sQuery2 =
            @"SELECT TimeId, TimingPoint, MacAddress, ChipCode, ... FROM ChipTime WHERE MacAddress = @MacAddress AND ClientId = @ClientId ORDER BY CreateDate Desc";
        var chipTimes = dbConnection.Query<ChipTime>(sQuery2, new {ClientId = clientId, MacAddress = id}).ToList();
    }

答案 1 :(得分:0)

一个答案,我希望你不介意我说,将使用QueryFirst而不是Dapper。你的ChipTime poco将由该工具生成,因此你没有机会做错。无需创建(和维护)POCO即可获得强大的输入。

免责声明:我写过QueryFirst。