Dapper:是否可以自定义特定类型的特定字段的类型映射? [英] Dapper: is it possible to customize the type mapping of a specific field of a specific type?

查看:517
本文介绍了Dapper:是否可以自定义特定类型的特定字段的类型映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说我有这个User课:

public class User
{
    public int      ID          { get; set; }
    public string   FirstName   { get; set; }
    public string   LastName    { get; set; }
    public string   Email       { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime LastLogin   { get; set; }
}

我想映射到下表:

CREATE TABLE "user" (
  "ID"          int(11) NOT NULL AUTO_INCREMENT,
  "FirstName"   varchar(45) DEFAULT NULL,
  "LastName"    varchar(45) DEFAULT NULL,
  "Email"       varchar(255) NOT NULL,
  "DateCreated" int(11) NOT NULL,
  "LastLogin"   int(11) NOT NULL,
  PRIMARY KEY ("ID")
)

或更简单地说:我想将DateTime属性存储为数据库中的int字段.但是,此类/表就是这种情况.其他类/表的映射方式可能有所不同.我正在考虑将自定义转换函数与类型或成员映射结合使用.

Or put in simpler words: I want to store the DateTime properties as int fields in the database. However, this is the case for this class/table. Other class/tables might be mapped differently. I was thinking of something along the lines of a custom conversion function in combination with type or member map.

是否可以使用Dapper做到这一点?如果可以,怎么办?

Is it possible to achieve this with Dapper, and if so how?

推荐答案

最重要的是Dapper在设计上不支持此功能.它的核心设计原则之一是表和对象之间的1:1映射,但列名到属性名的映射除外.

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.

我最后使用的解决方案是将Dapper与AutoMapper结合起来,无论如何我们已经大量使用了.在我们的Dapper DAO中,在复杂情况下,我们使用与域对象分开的实体对象并在它们之间进行映射.因此,从本质上讲,域和表之间的非平凡映射成为对象到对象映射的简单问题.

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:是否可以自定义特定类型的特定字段的类型映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆