Best Data annotation for a Decimal(18,2)

后端 未结 8 1299
無奈伤痛
無奈伤痛 2020-12-14 05:57

I have a column inside my sql server 2008 wih type of Decimal(18,2). But on entity framework what is the best data annotation validation I can apply to this pro

相关标签:
8条回答
  • 2020-12-14 06:35

    If you write the 'column' annotation, will work fine

        [Required]
        [Column(TypeName = "decimal(18, 6)")]
        public decimal Foo { get; set; }
    
    0 讨论(0)
  • 2020-12-14 06:40
     [Range(1,(double) decimal.MaxValue, ErrorMessage="value should be between{1} and {2}."]
    
    0 讨论(0)
  • 2020-12-14 06:41

    There is no explicit data annotation for a decimal so you need to use two separate ones to add constraints.

    Two Decimal Points

    [RegularExpression(@"^\d+\.\d{0,2}$")]
    

    This regular expression will make sure that the property has at most two decimal places.

    Max 18 digits

    [Range(0, 9999999999999999.99)]
    

    Assuming you aren't accepting any negative numbers. Otherwise, replace 0 with -9999999999999999.99.

    Result

    [RegularExpression(@"^\d+\.\d{0,2}$")]
    [Range(0, 9999999999999999.99)]
    public decimal Property { get; set; }
    
    0 讨论(0)
  • 2020-12-14 06:44

    For a different approach which some may consider more readable, you can override the OnModelCreating method of your DbContext to set precision, like so:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
    
               modelBuilder.Entity<YourEntity>()
                        .Property(x => x.TheProprty)
                        .HasPrecision(18, 2);
        }
    

    Advantage: strongly typed vs custom regular expression

    Disadvantage: can't see it on the class with just a scan

    0 讨论(0)
  • 2020-12-14 06:46

    This seems to be the correct answer ( the above answers either restrict valid numbers that can be inserted into a data type of Decimal(18,2) or cause compile errors if you apply them to your code -- please confirm for yourself):

    Use the following two constraints together:

    Two Decimal Points

    [RegularExpression(@"^\d+.?\d{0,2}$", ErrorMessage = "Invalid Target Price; Maximum Two Decimal Points.")]
    

    Max 18 digits

      [Range(0, 9999999999999999.99, ErrorMessage = "Invalid Target Price; Max 18 digits")]
    
    0 讨论(0)
  • 2020-12-14 06:49

    Following on from @Schmalls example (and comment re building it into an attribute) I've created a working example (uses C# 6 string interpolation):

    public class PrecisionAndScaleAttribute : RegularExpressionAttribute
    {
        public PrecisionAndScaleAttribute(int precision, int scale) : base($@"^(0|-?\d{{0,{precision - scale}}}(\.\d{{0,{scale}}})?)$")
        {
    
        }
    }
    

    Usage:

    [PrecisionAndScale(6, 2, ErrorMessage = "Total Cost must not exceed $9999.99")]
    public decimal TotalCost { get; set; }
    
    0 讨论(0)
提交回复
热议问题