问题
just started to use Dapper and like it. I'm having a problem with it, it returns the right number of objects, butthey all have default values for their properties
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 just has a list of ChipTime objects, all of which just have the default properties and not the values from the database
If I do
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();
}
The dynamics all have the right values in
ChipTime class is really simple
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; }
}
What am I doing wrong?
回答1:
Try to specify the names of columns that you want to select in your query instead of doing a 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?
I tried this but same results.
Make sure that the columns in your ChipTime table exactly matches the property names of your ChipTime class and specify the type argument (dbConnection.Query <ChipTime>):
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();
}
回答2:
One answer, I hope you don't mind me saying, would be to use QueryFirst instead of Dapper. Your ChipTime poco will be generated by the tool, so you've no chance to do it wrong. You get the strong typing without having to create (and maintain) a POCO.
Disclaimer : I wrote QueryFirst.
来源:https://stackoverflow.com/questions/41149588/dapper-strongly-typed-query-returning-default-object-values