c# - 使用 Dapper 将两个数据库列映射到一种数据类型

标签 c# dapper

dapper 是否有可能将数据库中的两列映射到一种 .Net 数据类型?
我的情况是,数据库中的货币值表示为两列。

Cost         Decimal(19,4)  
CostCurrency char(3)

我希望它映射到自定义数据类型 Money

public partial struct Money
{
   public Money(decimal amount, string currency)
   {
   }
}

以保险实体为例:

public class Insurance
{
    public string Id {get;set;}
    public Money Cost {get;set;}
}

我一直在看SqlMapper.TypeHandler<Money>但它似乎一次只能读/写一列。

最佳答案

我倾向于发现,通过使用私有(private)属性来表示数据存储,可以大大简化复杂属性的任何映射。 Dapper 将映射到私有(private)属性。

public class Insurance
{
    #region Data
    private decimal Cost{get{return this.CurrentCost.Amount;} set{this.CurrentCost.Amount = value;}}
    private string Currency{get{return this.CurrentCost.Currency;} set{this.CurrentCost.Currency = value;}}
    #endregion


    public string Id {get;set;}

    //Changed prop name to not confuse it with storage columns
    public Money CurrentCost {get;set;}

    public Insurance(){
        //initialize this so that it won't blow up on mapping
        this.CurrentCost = new Money();
    }
}

乍一看,这感觉就像我们对我们的对象做了很多标记,以使其持久化和映射。但它非常简单,没有任何神奇的映射,所以它就可以工作。您也可以对所有这些进行单元测试。即使是一个具有数百个持久对象的项目,这种技术也只会占用一小部分时间,并且在项目的整个发展过程中完全灵活且易于管理。

关于c# - 使用 Dapper 将两个数据库列映射到一种数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37806636/

相关文章:

c# - WPF 数据网格组合框列 : how to manage event of selection changed?

c# - 用asp传递参数:Button onClick with x-jquery-tmpl

c# - 子字符串上的 ComboBox 自动完成

oracle - 无法使用 Dapper 将 bool 值插入 Oracle

c# - Dapper Oracle Number(10,0) 作为 Decimal Parser 错误返回

c# - using var 总是被执行吗?

c# - 在域事件中包含用户 ID

Dapper 扩展获取和更新返回错误

c# - SQL Server session 上下文限制

c# - 如何在 Sqlite 中使用 Dapper.QueryMultiple