I'm using Dapper in a repository to map results of a query to a list of a DTO type for my API to return. Everything seems to be working right but after the query and mapping is finished, the correct number of objects are populated in the list, but all the int properties are 0 and strings are null. I've used Dapper quite a bit on other projects and never run into this before. I've also verified that the data is correct, and if I copy the query to SQL Management Studio it gives me the correct data.
Here's the constructor for my repository base class containing the custom mapping logic. I confirmed this code is getting hit.
static BaseRepository()
{
SqlMapper.SetTypeMap(typeof(T),
new CustomPropertyTypeMap(
typeof(T), (type, columnName) => type.GetProperties()
.FirstOrDefault(prop => prop.GetCustomAttributes(false)
.OfType<ColumnAttribute>()
.Any(attr => attr.Name == columnName))));
}
Here is the repository method to populate the list:
public IEnumerable<Dog> GetAll()
{
var dogs = Db.Query<Dog>(@"SELECT Id, Name FROM Dogs");
return dogs;
}
And here is my object:
[DataContract]
public class Dog
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
}
So I've confirmed that the "dogs" variable gets populated, but all the Id and Name elements are 0 or null. Here's what the final JSON result looks like:
[
{
Id: 0,
Name: null
},
{
Id: 0,
Name: null
},
{
Id: 0,
Name: null
}
]
I've also tried adding column attributes to the properties, like [Column(Name = "Id")]
. Still no luck. What am I overlooking?
Edit: I was able to resolve this issue using the example code and gist in this related answer.
You seem to have a custom map that uses [Column("Id")]
etc to define / recognise the columns. However, you have not added this attribute - so no columns will be found...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With