我是mvc的新手,我尝试对我的控制器进行简单的Ajax调用,因此我可以在创建视图中使用日期和时间选择器。
您可以看到我之前请求帮助的thread。但现在我遇到了一个新问题。
我在尝试保存数据时遇到此错误: EntityFramework.dll中出现“System.Data.Entity.Infrastructure.DbUpdateException”类型的异常,但未在用户代码中处理
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 :(得分:1)
EntityFramework是对数据库(通常是SQL Server)的抽象。当您在EF中遇到异常时,通常是因为框架抓住了较低级别SQLException
,并且#34;包裹了#34;它作为InnerException
,然后重新开始。因此,当您查找EF异常时,请记住,您应该打开那些InnerExceptions
以找出问题的真正来源(通常是某种SQLException
,并提供更有帮助的消息)
在这种情况下,希望你现在明白你正在尝试使用外键表中不存在的外键值。
至于你的MVC代码,@ Steve Muecke是正确的,你不需要总是声明字符串类型作为你的动作方法参数类型。当然,他们通过HTTP作为文本进入,但MVC的ModelBinder是强大的工具,能够将这些文本值转换为DateTime
s,int
,甚至包含其他基元的复杂类型和结构
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");
}
答案 1 :(得分:0)
从InnerException
的{{1}}可以看出,主要错误是:
INSERT语句与FOREIGN KEY约束冲突 &#34; FK_Sammantrade_Lokal&#34 ;.冲突发生在数据库&#34; VLVision&#34;中, table&#34; dbo.Lokal&#34;,column&#39; lID&#39;
因此,您将无效值传递给字段:DbUpdateException
,这段代码中的引用表lID
中不存在该值:
dbo.Lokal