强制 EF 保存指定的小数位

Force EF to save specified decimal places

我在我的实体中定义了一些 decimal 属性:

public class Entity1
{
   public int Id { get; set; }

   public decimal Value {get; set;}
}

并且因为我想为我的小数保存 maximum 4 个小数位,所以在我的配置文件中我定义了:

this.Property(t => t.Value).HasPrecision(18, 4); 

所以结果是 Value 字段,在我的 Entity1 table.

中有 4 个小数位

如何强制 EF 只保存 Value 值中使用的小数位?

例如:

换句话说,我想 EF 保存最终用户在 Value 中指定的小数位。

由于您关心的是如何按照输入的方式显示数字,而不是出于数学原因保留精确的精度,因此您有几个选择。

我假设您实际上需要该值在数据库中为数字,以用于查询或计算目的。否则,您可以将其保存为字符串。

您可以保存第二个值,表示输入值的精度,并使用它为您的值创建格式字符串:

public decimal  Value { get; set; }
public byte     ValuePrecision { get; set; }

public string FormatValue()
{
    string fmtString = string.Format("{{0:N{0}}}", this.ValuePrecision);
    return string.Format(fmtString, this.Value);
}

免责声明:代码是凭记忆完成的,未经测试。