【问题标题】:Automapper rounding down decimal / removing precisionAutomapper 舍入小数/去除精度
【发布时间】:2020-02-13 13:05:53
【问题描述】:

我正在将实体模型映射到 UI 模型,但是在映射完成后,几个字段正在向下舍入。所有受影响的字段都是相同的类型 decimal? ,当从数据库中提取它时,该字段是 8245.82 但是一旦映射它是 8245.00

public IActionResult View(Guid Id)
{
     try
     {
           DealEx entity = _dealService.Get(m => m.Id == Id);
           var model = _mapper.Map<DealUI>(entity);
           AddReferenceData(model);
           return PartialView("_deal", model);
       }
       catch (Exception ex)
       {
           this.ProcessException(ex, _logger);
           return View("Error");
        }
}

我假设这是 Automapper 中的内容?当 entity 模型被拉出时,值是正确的,然后我对其进行映射,并且 model 中的值现在向下舍入。

可能还值得一提的是 DealUI 继承了 DealEx 。

public class DealUI : DealEx
{
    public DealUI()
    {
    }

    // just some select lists in here , northing of interest to this 
}
public class DealEx
{
   public DealEx(){}

   public decimal? BillValue {get; set;}

   // obivously alot more in this model but it's a big ole model so copying  it all seems a bit pointless
}

包括映射要简洁

 CreateMap<DealEx, DealUI>();
 CreateMap<DealUI, DealEx>();

干杯

【问题讨论】:

  • 复制会有所帮助。创建一个gist,我们可以执行并看到失败。
  • 添加 DealEx 、 DealUI 和映射器会有所帮助。
  • 对不起,我第一次误解了你的问题,我现在添加了。干杯

标签: c# asp.net .net automapper


【解决方案1】:

试试这个:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<NameOfEntity>()
                    .Property(p => p.NameOfProperty)
                    .HasPrecision(9, 4); // or whatever your schema specifies
    }

【讨论】:

  • 您好,Kasper,感谢您的帮助。我实际上使用的是 MariaDb,小数点是 (65,30) 。
  • 我已经更新了我的答案,有一些你可以尝试的代码
  • 我刚刚看了看,似乎 SqlProviderServices 是针对 SqlServer 的,我的想法是对的吗? ...无论哪种方式,当从数据库中提取值时它们都是正确的(尽管尾随为 0),只有在映射它们时才会向下舍入。
  • 等一下,您的小数精度设置为 (65,30)?我不确定你能有这么大的小数
  • mysqltutorial.org/mysql-decimal 好像可以,这一定是 MariaDb 中的默认设置
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-26
  • 1970-01-01
  • 2020-02-29
  • 1970-01-01
  • 1970-01-01
  • 2011-01-22
  • 1970-01-01
相关资源
最近更新 更多