参数异常参数值超出十进制范围

时间:2019-03-05 09:58:01

标签: c# sql-server asp.net-mvc entity-framework decimal

在数据库price列中设置为decimal(20, 2)

这意味着它可以保留小数点前的18位数字和小数点后的2位数字。对吧?

现在,当我尝试保存值12345678.00时,它说:parameter value is out of range

我做错了什么?

更新

123456.00 is saved in db.
1234567.00 gives exception

例外:

  

System.Data.Entity.Infrastructure.DbUpdateException:更新条目时发生错误。有关详细信息,请参见内部异常。 ---> System.Data.Entity.Core.UpdateException:更新条目时发生错误。有关详细信息,请参见内部异常。 ---> System.ArgumentException:参数值'12345678.00'超出范围。在System.Data.SqlClient.TdsParser.TdsExecuteRPC(SqlCommand cmd,_SqlRPC [] rpcArray,Int32超时,布尔inSchema,SqlNotificationRequest notificationRequest,TdsParserStateObject stateO0bj,布尔isCommandProc,布尔同步,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完成,Int32超时,Task& 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.FromAsyncImpl(Func 3 beginMethod, Func 2 endFunction,Action 1 endAction, Object state, TaskCreationOptions creationOptions) at System.Threading.Tasks.TaskFactory 1.FromAsync上的任务,布尔值和使用过的缓存,布尔值asyncWrite,布尔值inRetry) (Func 3 beginMethod, Func 2 endMethod,对象状态),位于System.Data.SqlClient.SqlCommand.ExecuteNonQueryAsync(CancellationToken cancelledToken)---从上一个引发异常的位置开始的堆栈跟踪---位于System.Runtime.CompilerServices System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)在System.Data.Entity.Utilities.TaskExtensions.CultureAwaiter 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()处的TaskAwaiter.ThrowForNonSuccess(任务任务)追溯以前引发异常的位置---在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task任务)在System.Data.Entity.Core.Object.ObjectContext.d__39的System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) .MoveNext()-从上一个引发异常的位置开始的堆栈跟踪--在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务)处的System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) 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.GetResult()

更新

我创建了一个新数据库并运行迁移,以确保db列正是我所期望的,并且它是:

enter image description here

完整代码:

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类:

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"/>
                    }

控制器:

    [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 });
    }

1 个答案:

答案 0 :(得分:0)

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