mvc4 - db.SaveChanges() - decimal value out of ran

2019-05-14 08:37发布

问题:

I'm building an MVC4 application that requires me to generate a 21 digit key when 'creating' a new record.

Here is my context where i'm defining the db columns:

public class cust
    {
        public int ID { get; set; }

        public decimal CPCUST_KEY { get; set; }

        public decimal CPCUST_TOKEN { get; set; }

        public decimal CPCUST_ALTERNATE_KEY { get; set; }

In my SQL Server table the items are all set as 'decimal(38, 0)'...I believe I should be using a decimal data type? Somehow i'm still getting the out of range error below. My number is well within the 38 digit max length of my SQL variable.

System.Data.Entity.Infrastructure.DbUpdateException was unhandled by user code
  HResult=-2146233087
  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 Portal.Controllers.custController.Create(cust cust) in c:\Users\mwallace\Documents\Visual Studio 2012\Projects\Portal\Portal\Controllers\custController.cs:line 56
       at lambda_method(Closure , ControllerBase , Object[] )
       at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeSynchronousActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
       at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
       at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
       at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayaClass39.<BeginInvokeActionMethodWithFilters>b__33()
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
  InnerException: System.Data.UpdateException
       HResult=-2146233087
       Message=An error occurred while updating the entries. See the inner exception for details.
       Source=System.Data.Entity
       StackTrace:
            at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
            at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
            at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
            at System.Data.Entity.Internal.InternalContext.SaveChanges()
       InnerException: System.ArgumentException
            HResult=-2147024809
            Message=Parameter value '137090248607999999999.00' is out of range.
            Source=System.Data
            StackTrace:
                 at System.Data.SqlClient.TdsParser.TdsExecuteRPC(_SqlRPC[] rpcArray, Int32 timeout, Boolean inSchema, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, Boolean isCommandProc, Boolean sync, TaskCompletionSource`1 completion, Int32 startRpc, Int32 startParam)
                 at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
                 at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
                 at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
                 at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
                 at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
                 at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
                 at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
                 at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
            InnerException: 

This is the db.SaveChanges() line Visual Studio takes me to when it bombs.

// POST: /cust/Create

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(cust cust)
{
    if (ModelState.IsValid)
    {
        db.cpcust.Add(cust);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(cust);
}

回答1:

Found what the deal is between these two threads:

How do I prevent decimal values from being truncated to 2 places on save using the EntityFramework 4.1 CodeFirst?

Decimal precision and scale in EF Code First

Specifically applying this code to mine:

public class MyContext : DbContext
{
    public DbSet<Metrics> Metrics { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Metrics>().Property(x => x.PPM).HasPrecision(4, 3);
    }
}