Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF retrieves incorrect decimal precision

I'm using Entity Framework 6.1, code-first. I'm trying to store/retrieve a decimal from SQL Server, but the correct precision isn't retrieved. I read from a .csv file, process the data, then insert into the DB.

  • Value in the .csv file: 1.1390
  • Value when saved as decimal from the import: 1.1390
  • Value inserted into DB: 1.139
  • Value actually stored/shown in SSMS: 1.1390
  • Value when manually running the query SQL Profiler captures for the retrieval: 1.1390
  • Value retrieved by EF: 1.1300

Everything is working except for retrieving the value. I've tried the solution given in every single other SO post (below), but it has no effect. What's going wrong here? How can I retrieve the correct value with the proper precision?

Supposed solution:

modelBuilder.Entity<ClassA>().Property(p => p.MyDecimal).HasPrecision(19, 4);

Retrieval method, returns type ClassA with incorrect precision:

_poRepository.Table.FirstOrDefault(p => p.CompNumberA == compNum && 
                                        p.LineNumber == lineNumber);

Comparison between the two decimal values:

import.MyDecimal != dbValue.MyDecimal

ClassA:

public class ClassA
{
    // properties
    public virtual decimal MyDecimal { get; set; }
}
like image 424
vaindil Avatar asked Jan 13 '16 19:01

vaindil


2 Answers

Turns out I needed to specify the precision the same way, but in the fluent mapping for ClassA. Specifying it in OnModelCreating() didn't do it, but in the fluent mapping did. Specifically:

Property(u => u.MyDecimal).HasPrecision(19, 4);
like image 74
vaindil Avatar answered Sep 20 '22 17:09

vaindil


In Entity Framework Core you can do:

[Column(TypeName = "decimal(19,4)")]
public decimal MyDecimal { get; set; }
like image 25
Yoann Kergall Avatar answered Sep 23 '22 17:09

Yoann Kergall