![](/img/trans.png)
[英]c# conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value
[英]Entity Framework: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value C#
我有一個班級公告:
namespace WebApplication2.Models {
public partial class Announcment {
public int Id { get; set; }
[DisplayName("Subject")]
public String Subject { get; set; }
[DataType(DataType.MultilineText)]
[DisplayName("Content")]
public String Text { get; set; }
[DisplayName("Published")]
public DateTime TimeStamp { get; set; }
[DisplayName("Author")]
public virtual ApplicationUser Author { get; set; }
}
}
我就這樣創建它 日期時間TimeStamp
自動設置為DateTime.Now
:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Subject,Text")] Announcment announcment) {
if (ModelState.IsValid) {
//MINE
var user = UserManager.FindById(User.Identity.GetUserId());
Debug.WriteLine("USER" + user.Id);
announcment.TimeStamp = DateTime.Now;
announcment.Author = user;
//
db.Announcments.Add(announcment);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(announcment);
}
它的工作沒有任何麻煩。 沒有錯誤。
但是然后我要對其進行編輯。 用於編輯的視圖如下所示。 這是Visual Studio 2013生成的標准Edit
操作。我剛剛刪除了@model.TimeStamp
編輯器。
@model WebApplication2.Models.Announcment
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Announcment</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.Subject, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Subject, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Subject, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Text, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Text, new { htmlAttributes = new { @class = "form-control", rows = 8} })
@Html.ValidationMessageFor(model => model.Text, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
然后運行POST Edit
方法。 我在這里所做的唯一一件事就是刪除對,TimeStamp
綁定,TimeStamp
因為我沒有對其進行編輯。 有或沒有它我都得到相同的結果。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Subject,Text")] Announcment announcment) {
if (ModelState.IsValid) {
db.Entry(announcment).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(announcment);
}
我得到這個邪惡的錯誤:
Błąd serwera w aplikacji '/'.
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
Opis: Podczas wykonywania bieżącego żądania sieci Web wystąpił nieobsługiwany wyjątek. Aby uzyskać dodatkowe informacje o błędzie i miejscu jego występowania w kodzie, przejrzyj ślad stosu.
Szczegóły wyjątku: System.Data.SqlClient.SqlException: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
Błąd źródła:
Wiersz 86: Debug.WriteLine(announcment.TimeStamp);
Wiersz 87: db.Entry(announcment).State = EntityState.Modified;
Wiersz 88: db.SaveChanges();
Wiersz 89: return RedirectToAction("Index");
Wiersz 90: }
Plik źródłowy: c:\Users\R\Documents\Visual Studio 2013\Projects\WebApplication2\WebApplication2\Controllers\AnnouncmentsController.cs Wiersz: 88
Ślad stosu:
[SqlException (0x80131904): The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +1789294
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5340642
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +244
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1691
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +275
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) +1421
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +177
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +208
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +163
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c) +36
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +138
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext) +476
System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery() +177
System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues) +1382
System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() +236
[UpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() +488
System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut) +32
System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update(T noChangesResult, Func`2 updateFunction) +272
System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update() +143
System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35() +34
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +448
System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction) +219
System.Data.Entity.Core.Objects.<>c__DisplayClass2a.<SaveChangesInternal>b__27() +71
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +211
System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction) +408
System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options) +39
System.Data.Entity.Internal.InternalContext.SaveChanges() +320
[DbUpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Data.Entity.Internal.InternalContext.SaveChanges() +366
System.Data.Entity.Internal.LazyInternalContext.SaveChanges() +56
System.Data.Entity.DbContext.SaveChanges() +52
WebApplication2.Controllers.AnnouncmentsController.Edit(Announcment announcment) in c:\Users\R\Documents\Visual Studio 2013\Projects\WebApplication2\WebApplication2\Controllers\AnnouncmentsController.cs:88
lambda_method(Closure , ControllerBase , Object[] ) +181
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +434
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +60
System.Web.Mvc.Async.ActionInvocation.InvokeSynchronousActionMethod() +76
System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +36
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +73
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +117
System.Web.Mvc.Async.<>c__DisplayClass48.<InvokeActionMethodFilterAsynchronouslyRecursive>b__41() +323
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9690172
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Informacje o wersji: Wersja Microsoft .NET Framework:4.0.30319; Wersja ASP.NET:4.0.30319.34009
問題:什至不嘗試編輯Announcment
TimeStamp
屬性時,為什么會出現此異常? 如何解決這個問題?
編輯:我發現即使我不嘗試編輯原始日期,它也被神秘地設置為: 0001-01-01 00:00:00
在編輯帖子時,您還必須綁定TimeStamp
屬性,在空情況下,它將采用帖子中顯示的值,因此如果您不希望用戶更改它,請將其放在隱藏字段中:
@Html.HiddenFor(m=>m.TimeStamp)
否則,它將被發布為null,在這種情況下,它將在數據庫端更改為0001-01-01 00:00:00
,這是無效的DateTime
並且您將獲得異常
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.