Pasting the decimal fraction in sql causes zero to be inserted. Instead of a decimal close to zero

During insertion, a floating point number, for example 0.0001 in sql from my code, the result is 0.0000 in the database. here is the column definition of my table:

decimal(20,15) 

Here is the class field definition:

 public decimal Rate {get ; set; } 

How can I solve this problem?

I use the first EF Code approach as follows:

 Class1 obj = new Class1(); obj.Rate = 0.000001; ClassDbSet.Add(obj); DbContext.SaveChange(); 
+5
source share
2 answers

I have encountered this problem for a long time. Add this method (if it does not exist) to the DbContext:

 protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Class1>().Property(rec => rec.Rate).HasPrecision(20, 15); } 

when you declare such a variable in EF and don’t mention how much precision the floating-point number has, so the EF Engine assumes the default value (decimale (18,2))

+3
source

If you are using EF 4.1 or higher, override the OnModelCreating method and specify Precision for the decimal column in EF. See ( Decimal Accuracy and Scale in EF Code First ).

 public class EFDbContext : DbContext { protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) { modelBuilder.Entity<Class1>().Property(object => object.Rate).HasPrecision(20,15); base.OnModelCreating(modelBuilder); } } 
+1
source

Source: https://habr.com/ru/post/1207675/


All Articles