1

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, TaskCompletionSource1 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, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 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.TaskFactory1.FromAsyncImpl(Func3 beginMethod, Func2 endFunction, Action1 endAction, Object state, TaskCreationOptions creationOptions) at System.Threading.Tasks.TaskFactory1.FromAsync(Func3 beginMethod, Func2 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.CultureAwaiter1.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__3d1.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.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__91.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.TaskAwaiter1.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:

enter image description here

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 });
    }
Irfan Y
  • 1,242
  • 2
  • 21
  • 68
  • there is something else wrong..12345678.00 is valid value for decimal(20,2), may be problem with the length of your input variable of the stored procedure. – PSK Mar 05 '19 at 10:01
  • Error could be due to some other reason as 12345678.00 value can be stored in decimal(20, 2) column. try to pass some lower value and see the result. if still get the error with lower value then it will be confirmed the error due to some other column. – Mukesh Arora Mar 05 '19 at 10:01
  • Are you sure this is the entity/property resulting in the error? If yes, do you have any column mapping there? – DevilSuichiro Mar 05 '19 at 10:01
  • Post the code that actually throws and the *full* exception, including the call stack. You can get that easily with `Exception.ToString().` Don't post parts of the exception. The full string contains any inner exceptions, extra information and the full call stack – Panagiotis Kanavos Mar 05 '19 at 10:02
  • Probably you should look for [this post](https://stackoverflow.com/questions/20264558/entityframework-parameter-value-is-out-of-range), which has similar 2 decimal places problem. It uses `HasPrecision` method to set decimal precision. – Tetsuya Yamamoto Mar 05 '19 at 10:02
  • What does the entity's configuration look like? Any precision attributes or context configuration? EF itself will validate that a value matches the property's precision – Panagiotis Kanavos Mar 05 '19 at 10:05
  • Please check updated question – Irfan Y Mar 05 '19 at 10:07
  • It would be awesome if you could provide a [mcve]. This must include the code that explicitly sets the property value. – mjwills Mar 05 '19 at 12:25
  • I have added complete code, please see updated question, please let me know if its still not clear. – Irfan Y Mar 05 '19 at 13:01

1 Answers1

0

check price datatypes in db, may be you used different datatypes in db

  • First line of my question tells about data type of db column – Irfan Y Mar 05 '19 at 10:23
  • 1
    @IrfanYusanif - it is always worth double checking the table has been created exactly as you think it should have been & not relying at looking at the code you have now. – PaulF Mar 05 '19 at 10:40
  • @PaulF you're right, I created new database to make sure that db column is exactly what i'm expecting, and i have posted table screen shot in question as well. – Irfan Y Mar 05 '19 at 10:53
  • @IrfanYusanif: That shows the table is correct & should be able to correctly store the value. How do you set Price to '12345678.00' - databinding to a control or assignment in code - seeing that code may help. – PaulF Mar 05 '19 at 11:00
  • @PaulF, i have updated the question, please have a look – Irfan Y Mar 05 '19 at 11:21
  • Have You check parameter type in RPC? – Amit Vekaria Mar 05 '19 at 12:06
  • @AmitVekaria, no, how to check and in which RPC? – Irfan Y Mar 05 '19 at 12:21