Why do my objects returned from Dapper have null and default property values?

.net c# dapper

Question

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.

Expert 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...



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