Inserting a decimal into sql cause inserting a zero number Instead of a decimal number near zero
Asked Answered
A

2

6

During insert a float number like 0.0001 into sql from my code, the result is a 0.0000 in database. here is definition of my table column:

decimal(20,15) 

Here is the definition of class field:

public decimal Rate {get ; set; }

How can I solve this problem?

I am using EF Code first approach like this:

Class1 obj = new Class1();
obj.Rate = 0.000001;
ClassDbSet.Add(obj);
DbContext.SaveChange();
Aldosterone answered 25/11, 2014 at 15:10 Comment(3)
Can you show the code that is actually inserting the value into your DB.Peyton
More info on the database server you are using might be helpful.Standfast
Also show how you are retrieving/displaying this valueCore
W
4

I have be encounter with this issue long time ago. Add this method (if not exists) into you DbContext :

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

when you declare a variable like this in EF and do not mention any thing about how many precision the float number have , so EF Engine accept the default value (decimale(18,2))

Womankind answered 25/11, 2014 at 15:22 Comment(0)
R
1

If you are using EF 4.1 or above override the OnModelCreating method and specify Precision for decimal column in EF. See (Decimal precision and scale in EF Code First) post.

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);
   }
}
Rodman answered 25/11, 2014 at 15:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.