How to skip auto property mapping in entity framework

Deshmukh, Vivek 1 Reputation point
2022-08-11T13:00:52.467+00:00

We are using EF code first and need to store (38,23) decimal values. Understood that its not possible in C# as C# supports only max 29 digits. But SQL can store this value so we could able to generate SQL column to (38,23) using following code. Class Definition is

 public class CryptoEvN  
{  
    [Key]  
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
    public int EvId { get; set; }  
  
    public decimal? Quantity { get; set; }  
     
    public decimal? Price { get; set; }  
}  

Fluent API

 public class AppDataContext : DbContext  
{  
    public AppDataContext()  
        : base("name=AppDataContext")  
    {  
    }  
    public DbSet<CryptoEvN> CryptoEvNs { get; set; }  
  
    protected override void OnModelCreating(DbModelBuilder modelBuilder)  
    {  
        modelBuilder.Conventions.Remove<DecimalPropertyConvention>();  
        modelBuilder.Conventions.Add(new DecimalPropertyConvention(38, 23));  
    }  
}  

It generates a SQL table's Price and Quantity column as decimal(38,23)

This table's Price and Quantity field contains a value as 123456789012345.12345678901234567890123 which is 15 to the left and 23 to the right so total is (38,23)

Now when we tries to retrieve data using AppDataContext

AppDataContext appDataContext = new AppDataContext();  
var cryptoEvNs = appDataContext.CryptoEvNs.ToList();  

it gives exception as "Conversion Overflow" because C# doesn't support to hold this much long number.

We have tried using [NoMapped] but after adding this its removing the columns from table which we dont want to.

We have found that we can create our own custom BigDecimal to hold big number so once we skip this automapping will use this custom type binding by writing store procs and custom class mapping.

So how can we skip auto mapping of these two Price and Quantity properties or any other way by which we can map this BigDecimal to existing decimal property?

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,323 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,164 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,026 Reputation points
    2022-08-18T10:45:37.277+00:00

    Take a look at Value converters with BigDecimal.

    0 comments No comments