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(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.TaskFactory
1.FromAsyncImpl(Func3 beginMethod, Func
2 endFunction, Action1 endAction, Object state, TaskCreationOptions creationOptions) at System.Threading.Tasks.TaskFactory
1.FromAsync(Func3 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.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__3d
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.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.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 });
}