0

I´m new to mvc and I try to to do a simple Ajax call to my controller, so I can use a date- and timepickers in my create view.

You can see this thread where I previously asked for help. But now I have encountered a new problem.

I get this error when I try to save my data: An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code

 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);
    }

EDIT:

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: 
11
  • 2
    The exception contains all the information you need. However, you aren't looking in it. That's a big problem you need to solve. If you're debugging, the exception helper dialog has a "copy exception details to the clipboard" link on it. Use it. If you're in production, catch the bastard and call ToString() on it. That captures ALL details you need to know what's going on. Once you've got it, log it. Once you've done all this, edit and add the details to your question. Commented Sep 22, 2015 at 13:34
  • 1
    Its not a string! Every thing thats posted is just name/value pairs. Make the parameters DateTime and int and you can skip the ConvertTo() code. But change the name of the properties in your ajax call to math the model properties and then just use public ActionResult CreateEvent(Sammantrade model) so its all correctly bound. Commented Sep 22, 2015 at 13:37
  • 1
    But since its an ajax call, return RedirectToAction("Index"); make no sense (ajax call do not redirect). And your current use of if (ModelState.IsValid) makes even less sense. ModelState can never be invalid since your models are just 4 strings which can never be invalid. Commented Sep 22, 2015 at 13:39
  • 4
    Here is your real problem: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Sammantrade_Lokal". The conflict occurred in database "VLVision", table "dbo.Lokal", column 'lID'. The database doesn't like what you are providing for that foreign key value. Commented Sep 22, 2015 at 13:40
  • 1
    I don't really know why your questions attract so many upvotes, but it's basically an error dump. Read the error, try to understand it. Explain what you found and what you don't understand. Commented Sep 22, 2015 at 13:43

2 Answers 2

1

As it is obvious from InnerException of the DbUpdateException, the main error is :

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Sammantrade_Lokal". The conflict occurred in database "VLVision", table "dbo.Lokal", column 'lID'

So you are passing an invalid value to field: lID , a value that not exists in reference table dbo.Lokal in this line of code:

sammantrade.lID = Int32.Parse(createLokal);
Sign up to request clarification or add additional context in comments.

2 Comments

This same answer has already been added, downvoted, and deleted by another user because it was already addressed in comments. Do you have anything to add that wasn't already mentioned in OP comments?
@danludwig Thank you for your comment, I can add as addressed in comments, but many users doesn't read comments and they read answers, and I don't think this is a bad answer, this way it will be more useful for other users in the future :) and also can add try catch to be more useful. What's your idea?
1

EntityFramework is an abstraction over a database (usually SQL Server). When you encounter exceptions in EF, it's usually because the framework caught a lower level SQLException, "wrapped" it as an InnerException, then rethrew. So when you are hunting down EF exceptions, keep in mind that you should unwrap those InnerExceptions to find out the real source of the problem (which is usually some kind of SQLException with a much more helpful message).

In this case, hopefully it's obvious to you now that you were trying to use a foreign key value that did not exist in the foreign key table.

As for your MVC code, @Stephen Muecke is correct that you don't need to always declare string types as your action method argument types. Sure, they come in over HTTP as text, but MVC's ModelBinders are powerful tools that are able to translate those text values into DateTimes, ints, even complex types containing other primitives and structs.

It also looks like db is your DbContext instance, and that it is a private property on your Controller class. How are you disposing of it? Unless you have some kind of mechanism that will dispose of it, like an attribute, okay. Otherwise, you should be either wrapping your DbContext construction and usage in a using statement in each action method, or handling DbContext injection and disposal using an IoC container.

This would be better:

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 Comment

thanks dude ... your inner help concept give me clue to handle the error.. there was datetime coversion error @danludwig

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.