2015-09-22 47 views
0

我是mvc的新手,我嘗試對我的控制器執行一個簡單的Ajax調用,所以我可以在我的創建中使用日期和時間選擇器視圖。類型'System.Data.Entity.Infrastructure.DbUpdateException'的異常

您可以在此處查看thread我以前尋求幫助的地方。但是現在我遇到了一個新問題。

當我試圖挽救我的數據我得到這個錯誤: 型「System.Data.Entity.Infrastructure.DbUpdateException」的異常出現在EntityFramework.dll但在用戶代碼中沒有處理

public ActionResult CreateEvent(string createSammantrade, string createStartTime, string createEndTime, string createLokal) 
    { 
     Sammantrade sammantrade = new Sammantrade(); 


     sammantrade.sSammantrade = createSammantrade; 
     sammantrade.sStartTid = Convert.ToDateTime(createStartTime); 
     sammantrade.sSlutTid = Convert.ToDateTime(createEndTime); 
     sammantrade.lID = Int32.Parse(createLokal); 

     if (ModelState.IsValid) 
     { 
      db.Sammantrade.Add(sammantrade); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     ViewBag.lID = new SelectList(db.Lokal, "lID", "lLokal", sammantrade.lID); 
     return View(sammantrade); 
    } 

編輯:

System.Data.Entity.Infrastructure.DbUpdateException was unhandled by user code 
HResult=-2146233087 
Message=An error occurred while updating the entries. See the inner exception for details. 
Source=EntityFramework 
StackTrace: 
vid System.Data.Entity.Internal.InternalContext.SaveChanges() 
vid System.Data.Entity.Internal.LazyInternalContext.SaveChanges() 
vid System.Data.Entity.DbContext.SaveChanges() 
vid VLVision.Controllers.SammantradesAdminController.CreateEvent(String createSammantrade, String createStartTime, String createEndTime, String createLokal) 
vid lambda_method(Closure , ControllerBase , Object[]) 
vid System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) 
vid System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) 
vid System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) 
vid System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod> 
b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) 
vid System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) 
vid System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End() 
vid System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) 
vid System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive> 
b__3d() 
vid System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive> 
b__3f() 
InnerException: 
HResult=-2146233087 
Message=An error occurred while updating the entries. See the inner exception for details. 
Source=EntityFramework 
StackTrace: 
vid System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() 
vid System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update> 
b__2(UpdateTranslator ut) 
vid System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction) 
vid System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update() 
vid System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore> 
b__35() 
vid System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) 
vid System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction) 
vid System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal> 
b__27() 
vid System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation) 
vid System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction) 
vid System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options) 
vid System.Data.Entity.Internal.InternalContext.SaveChanges() 
InnerException: 
Class=16 
ErrorCode=-2146232060 
HResult=-2146232060 
LineNumber=1 
Message=The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Sammantrade_Lokal". The conflict occurred in database "VLVision", table "dbo.Lokal", column 'lID'. 
The statement has been terminated. 
Number=547 
Procedure="" 
Server=localhost\SQLExpress 
Source=.Net SqlClient Data Provider 
State=0 
StackTrace: 
vid System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) 
vid System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) 
vid System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) 
vid System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) 
vid System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() 
vid System.Data.SqlClient.SqlDataReader.get_MetaData() 
vid System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) 
vid System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest) 
vid System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) 
vid System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) 
vid System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) 
vid System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) 
vid System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) 
vid System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c) 
vid System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) 
vid System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) 
vid System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior) 
vid System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) 
vid System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues) 
vid System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() 
InnerException: 
+0

聽起來有類型的''InnerException' DbUpdateException'。那個例外的消息說什麼? – danludwig

+0

爲什麼參數'string'而不是'DateTime'和'int'?事實上,爲什麼不只是'公衆的ActionResult CreateEvent(Sammantrade模型)'? –

+0

您是否使用了正確的數據類型,或許您違反了主鍵?有沒有任何內在的例外給你更多的細節? –

回答

0

由於這是顯而易見的DbUpdateExceptionInnerException,主要錯誤是:

INSERT語句與FOREIGN KEY約束條件衝突 「FK_Sammantrade_Lokal」。衝突發生於數據庫「VLVision」, 表「dbo.Lokal」,列「蓋」

所以你傳遞一個無效的值到現場:lID,不是存在於參考表dbo.Lokal在這個值代碼行:

sammantrade.lID = Int32.Parse(createLokal); 
+0

這個相同的答案已經被其他用戶添加,下調和刪除,因爲它已經在註釋中解決了。你有什麼補充,這是沒有在OP評論中提到的? – danludwig

+1

@danludwig謝謝您的評論,我可以添加'在評論中提到',但許多用戶不閱讀評論,他們閱讀答案,我不認爲這是一個不好的答案,這樣它會更多對未來其他用戶有用:)並且還可以添加try catch以使其更有用。你的想法是什麼? –

1

EntityFramework是對數據庫(通常是SQL Server)的抽象。當你在EF中遇到異常時,通常是因爲框架抓到了一個較低級別SQLException,將它「包裝」爲InnerException,然後重新引發。因此,當您搜尋EF例外時,請記住,您應該拆開這些InnerExceptions以找出問題的真正根源(通常這是一種帶有更多幫助信息的某種SQLException)。

在這種情況下,希望您現在明白您正嘗試使用外鍵表中不存在的外鍵值。

至於你的MVC代碼,@Stephen Muecke是正確的,你不需要總是聲明字符串類型作爲你的動作方法參數類型。當然,他們通過HTTP作爲文本進入,但MVC的ModelBinder是功能強大的工具,能夠將這些文本值轉換爲包含其他基元和結構的複雜類型。

它也看起來像db是你的DbContext實例,它是你的Controller類的私有財產。你怎麼處理它?除非你有某種機制可以處理它,比如屬性,好吧。否則,您應該將每個操作方法中的DbContext構造和用法包裝在using聲明中,或者使用IoC容器處理注入和處置DbContext

這會更好:

if (ModelState.IsValid) 
{ 
    using (var db = new MyDbContext()) 
    { 
     db.Sammantrade.Add(sammantrade); 
     db.SaveChanges(); 
    } // the using block will dispose of the DbContext here. 

    return RedirectToAction("Index"); 
} 
+0

感謝兄弟......你內心的幫助概念給了我線索來處理錯誤..有日期時間蓋度誤差@丹盧維奇 – Rakeshyadvanshi

相關問題