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.
我在存储库中使用Dapper将查询结果映射到要返回的API的DTO类型列表。一切似乎都正常工作,但查询和映射完成后,列表中填充了正确的对象数量,但所有int属性都为0,字符串为空。我在其他项目中使用过Dapper,以前从未遇到过。我还验证了数据是正确的,如果我将查询复制到SQL Management Studio,它会给我正确的数据。
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:
我已经确认填充了“dogs”变量,但是所有的Id和Name元素都是0或null。最终的JSON结果如下:
[
{
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?
我还尝试向属性添加列属性,比如[column (Name = "Id")]。仍然没有运气。我俯瞰着什么呢?
Edit: I was able to resolve this issue using the example code and gist in this related answer.
编辑:我可以使用这个相关答案中的示例代码和主旨来解决这个问题。
1 个解决方案
#1
2
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...
您似乎有一个自定义映射,使用[Column("Id")]等来定义/识别列。但是,您还没有添加这个属性——因此不会发现任何列……
#1
2
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...
您似乎有一个自定义映射,使用[Column("Id")]等来定义/识别列。但是,您还没有添加这个属性——因此不会发现任何列……