I have a decimal property in Product entity:
public class Product
{
public Guid Id { get; set; }
public decimal Price { get; set; }
}
I want to config precision in model mapping:
class Context : DbContext
{
public DbSet<Product> Products { get; set; }
public Context() : base("server=localhost;database=myDb2;trusted_connection=true;")
{
/* Database.Delete();
Database.Create(); */
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().HasKey(e => new { e.Id });
modelBuilder.Entity<Product>().Property(s => s.Price).HasPrecision(29, 10);
}
}
Now I'm trying to save decimal that has 19 lengths:
using (Context context = new Context())
{
var product = new Product();
product.Id = Guid.NewGuid();
product.Price = 9999999999999999999M;
context.Products.Add(product);
context.SaveChanges();
}
It is throwing exception:
System.Data.Entity.Infrastructure.DbUpdateException HResult=0x80131501 Message=An error occurred while updating the entries. See the inner exception for details. Source=EntityFramework StackTrace: at System.Data.Entity.Internal.InternalContext.SaveChanges() at System.Data.Entity.Internal.LazyInternalContext.SaveChanges() at System.Data.Entity.DbContext.SaveChanges() at ConsoleApp11.Program.Main(String[] args) in C:\Users\dilshodk\source\repos\ConsoleApp11\ConsoleApp11\Program.cs:line 22
Inner Exception 1: UpdateException: An error occurred while updating the entries. See the inner exception for details.
Inner Exception 2: OverflowException: Conversion overflows.
When I try to insert value from SQL query it works:
Insert into Products values (NEWID(),9999999999999999999)
Why it is not working from EF and how can I solve it?
he he he. :o)
yes, you have a problem, you see - you defined it as (database type) decimal(29,10), that means 29 places, one for the dot, 10 for the digits (e.g. 0.0123456789 is valid, but 0.00123456789 will be written as 0.0012345678), leaving 18 places for the wholes (e.g. 123456789012345678 is fine but 19 digits of 9 is too big). Just set it up as HasPercision(30,10)
or HasPercision(29,5)
and you're good to go.
User contributions licensed under CC BY-SA 3.0