Dapper: is it possible to customize the type mapping of a specific field of a specific type?

浪子不回头ぞ 提交于 2019-12-04 12:17:01

The bottom line is that Dapper does not support this by design. One of its core design principles is a 1:1 mapping between the table and the object, with the exception of column names to property names mapping.

The solution I went with in the end was to combine Dapper with AutoMapper which we are already making heavy use of anyway. In our Dapper DAOs, in complex cases we use an entity object separate to the domain object and map between them. So essentially the non-trivial mapping between domain and table becomes a simple question of object-to-object mapping.

Dapper does not, to the best of my knowledge, currently support such conversions. You could use stored procs in Dapper, and have the proc do the conversion for you. You could also ensure that the data/conversion is done before passing the object to Dapper.

I heavily question why you'd opt for int dates vs DateTime however in your data source... Seems unnecessary and overly complex.

"Always write your code as if the next person to maintain it is an axe-wielding psychopath who knows your home address."

Dejan

Probably you can use the new SqlMapper.SetTypeMap method to achieve this. See https://stackoverflow.com/a/12615036/331281 for more information.

This should now be possible with custom SqlMapper.TypeHandler. See this example in unit tests. The downside is that it applies custom type handling to all fields of the same type. In your case all DateTime properties will be evaluated through type handler.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!