简体   繁体   中英

argument exception parameter value is out of range decimal

In database price column is set to decimal(20, 2) .

It means it can hold 18 digits before decimal and 2 digits after decimal point. Right?

Now when I try to save value 12345678.00 , it says: parameter value is out of range

What I'm doing wrong?

Update:

123456.00 is saved in db.
1234567.00 gives exception

Exception:

System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.ArgumentException: Parameter value '12345678.00' is out of range. at System.Data.SqlClient.TdsParser.TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, Int32 timeout, Boolean inSchema, SqlNotificationRequest notificationRequest, TdsParserStateObject stateO0bj, 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, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource 1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource 1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.BeginExecuteNonQueryInternal(CommandBehavior behavior, AsyncCallback callback, Object stateObject, Int32 timeout, Boolean inRetry, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.BeginExecuteNonQueryAsync(AsyncCallback callback, Object stateObject) at System.Threading.Tasks.TaskFactory 1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.BeginExecuteNonQueryInternal(CommandBehavior behavior, AsyncCallback callback, Object stateObject, Int32 timeout, Boolean inRetry, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.BeginExecuteNonQueryAsync(AsyncCallback callback, Object stateObject) at System.Threading.Tasks.TaskFactory 1.FromAsyncImpl(Func 3 beginMethod, Func 2 endFunction, Action 1 endAction, Object state, TaskCreationOptions creationOptions) at System.Threading.Tasks.TaskFactory 1.FromAsync(Func 3 beginMethod, Func 2 endMethod, Object state) at System.Data.SqlClient.SqlCommand.ExecuteNonQueryAsync(CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Data.Entity.Utilities.TaskExtensions.Cultu reAwaiter 1.GetResult() at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.<ExecuteAsync>d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.<UpdateAsync>d__0.MoveNext() --- End of inner exception stack trace --- at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.<UpdateAsync>d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Data.Entity.Core.Objects.ObjectContext.<ExecuteInTransactionAsync>d__3d 1.MoveNext() --- End of stack trace from previous l ocation where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Data.Entity.Core.Objects.ObjectContext.d__39.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.d__9 1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesInternalAsync>d__31.MoveNext() --- End of inner exception stack trace --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter 1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesInternalAsync>d__31.MoveNext() --- End of inner exception stack trace --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter 1.GetResult()

Update:

I created a new database and run migration to make sure that db column is exactly what I'm expecting, and here it is:

在此处输入图片说明

Complete code:

Ad.cs:

[Table("ad")]
public class Ad
{
        [Key, DatabaseGenerated(DatabaseGeneratedOption.None), Column("id")]
        public Guid Id { get; set; }
        [Column("price")]
        public decimal Price { get; set; }
        //other attributes
}

DbMigration class:

public partial class added_price_to_ad : DbMigration
    {
        public override void Up()
        { 
            AddColumn("dbo.ad", "price", c => c.Decimal(nullable: false, precision: 20, scale: 2));
        }

        public override void Down()
        { 
            DropColumn("dbo.ad", "images_count");
        }
    }

AdVm.cs:

public class AdVm
    {
        public string Id { get; set; }
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = 
        "{0:#.#}")]
        public decimal Price { get; set; }
        //other attributes
    }

create.cshtml:

@model ProjectName.ViewModels.AdVm
@using (Html.BeginForm("Save", "Ads", FormMethod.Post, new { id = "CreateAdForm" }))
                    {
                        @Html.AntiForgeryToken()

                        <div class="form-horizontal">
                            @Html.ValidationSummary(true)
                            @Html.HiddenFor(x => x.Id)

<div class="form-group">
                                @Html.LabelFor(model => model.Price, new { @class = "control-label col-md-2" })
                                <div class="col-md-10">
                                    @Html.EditorFor(model => model.Price)
                                    @Html.ValidationMessageFor(model => model.Price)
                                </div>
                            </div>

                        </div>
                       <input type="submit"/>
                    }

Controller:

    [HttpPost]
            [ValidateAntiForgeryToken]
    public async Task<ActionResult> Save(AdVm adVm)
   {
       var ad= Mapper.Map<AdVm, Ad>(adVm);
       db.Ads.Add(ad);
       await db.SaveChangesAsync(); //throws exception here
       return RedirectToAction("Details", new { id= ad.Id });
    }

检查数据库中的价格数据类型,可能是您在数据库中使用了不同的数据类型

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM