0

I have a column in a database table with a datatype of decimal(7, 3). When I enter this number (0.729) in input box, it will be updated to 0.730. I want to prevent this rounding. I have tried to set this data annotation to the field in the view model class, but it didn't work. I use ExecuteSqlInterpolatedAsync to execute the stored procedure but I can't find any way to solve that issue.

The action in the controller:

[HttpPost]
public async Task<IActionResult> UpdateElements(updateProductElementsViewModel model)
{
    var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

    if (!string.IsNullOrEmpty(userId))
    {
        await _appDbContext.Database.ExecuteSqlInterpolatedAsync($"exec SPApp_ProductElementsUpdate {userId},{model.id},{model.productName},{model.Density},{model.Ron}");
    }

    return RedirectToAction(nameof(HomeController.Index), "Home");
}

The stored procedure parameter:

@Density decimal(7,3)

The auto property on the updateProductElementsViewModel class:

[Column(TypeName = "decimal(7,3)")]
public decimal Density { get; set; }

The OnModelCreating method:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<updateProductElementsViewModel>()
                .Property(x => x.Density)
                .HasColumnType("decimal(7,3)");

    base.OnModelCreating(modelBuilder);
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
MR_WELL
  • 87
  • 1
  • 10
  • Do you use Attribute- and OnModelCreating- Mapping in parallel? Or did. you show, what you‘ve tried? – Nikolaus Dec 04 '20 at 20:31
  • @Nikolaus I found this after use the profiling in sql server Database.ExecuteSqlInterpolatedAsync will generate decimal(18,2) by default I think this is cause of the main issue ! – MR_WELL Dec 04 '20 at 20:39
  • I enabled logged to EF core and found this ( `Microsoft.EntityFrameworkCore.Database.Command: Information: Executed DbCommand (107ms) [Parameters=[@p3='0.729' (Precision = 18) (Scale = 2) ` ) by default the decimal precision = 18 and Scale =2 I have no idea how to ride this issue so I need increases the Scale part. – MR_WELL Dec 05 '20 at 08:10
  • Maybe this can help: [decimal in EFCore ](https://stackoverflow.com/questions/43277154/entity-framework-core-setting-the-decimal-precision-and-scale-to-all-decimal-p/43282620) – Nikolaus Dec 06 '20 at 15:00

0 Answers0