Visual-Studio WebApi Rest – Mysql db – Error when db.savechanges() with PUT

  Uncategorised

So i have an ASP.NET Web Application (.NET Framework) project where i have setup a REST webApi.
The database i utilized for my EF (EntityFramework) model is a Mysql database.

The model has been generated fine, and i have no trouble generating new controllers.

When calling the API to get information via. something like api/courses, i get the correct response, see below.

Api/Courses GET

[
    {
        "id": 1,
        "name": "Databases for developers",
        "ects": 10
    },
    {
        "id": 2,
        "name": "Testing",
        "ects": 10
    },
    {
        "id": 3,
        "name": "Development of large systems",
        "ects": 10
    },
    {
        "id": 4,
        "name": "DB test Course for api",
        "ects": 10
    }
]

so my controller Clearly connects to the model and the database correctly.

But when i try to use the webapi’s default PUT function

        // PUT: api/courses/5
        [ResponseType(typeof(void))]
        public IHttpActionResult Putcourse(int id, course course)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != course.id)
            {
                return BadRequest();
            }

            db.Entry(course).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!courseExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

I get the following error when i PUT via postman.

MySqlException: Table ‘roll_call_db.roll_call_db.course’ doesn’t exist

{
    "Message": "An error has occurred.",
    "ExceptionMessage": "An error occurred while updating the entries. See the inner exception for details.",
    "ExceptionType": "System.Data.Entity.Infrastructure.DbUpdateException",
    "StackTrace": "   at System.Data.Entity.Internal.InternalContext.SaveChanges()rn   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()rn   at System.Data.Entity.DbContext.SaveChanges()rn   at EducationAdmin.Controllers.coursesController.Putcourse(Int32 id, course course) in C:UsersMads OhmsensourcereposEducationAdminEducationAdminControllerscoursesController.cs:line 56rn   at lambda_method(Closure , Object , Object[] )rn   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_2.<GetExecutor>b__2(Object instance, Object[] methodParameters)rn   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)rn   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)rn--- End of stack trace from previous location where exception was thrown ---rn   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)rn   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)rn   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()rn--- End of stack trace from previous location where exception was thrown ---rn   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)rn   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)rn   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()rn--- End of stack trace from previous location where exception was thrown ---rn   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)rn   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)rn   at System.Web.Http.Controllers.AuthenticationFilterResult.<ExecuteAsync>d__5.MoveNext()rn--- End of stack trace from previous location where exception was thrown ---rn   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)rn   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)rn   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()",
    "InnerException": {
        "Message": "An error has occurred.",
        "ExceptionMessage": "An error occurred while updating the entries. See the inner exception for details.",
        "ExceptionType": "System.Data.Entity.Core.UpdateException",
        "StackTrace": "   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()rn   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<>c.<Update>b__21_0(UpdateTranslator ut)rn   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)rn   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()rn   at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__153_0()rn   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)rn   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)rn   at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass148_0.<SaveChangesInternal>b__0()rn   at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func`1 operation)rn   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)rn   at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)rn   at System.Data.Entity.Internal.InternalContext.SaveChanges()",
        "InnerException": {
            "Message": "An error has occurred.",
            "ExceptionMessage": "Table 'roll_call_db.roll_call_db.course' doesn't exist",
            "ExceptionType": "MySql.Data.MySqlClient.MySqlException",
            "StackTrace": "   at MySql.Data.MySqlClient.MySqlStream.ReadPacket()rn   at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)rn   at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)rn   at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)rn   at MySql.Data.MySqlClient.MySqlDataReader.NextResult()rn   at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)rn   at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()rn   at MySql.Data.EntityFramework.EFMySqlCommand.ExecuteNonQuery()rn   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<>c.<NonQuery>b__4_0(DbCommand t, DbCommandInterceptionContext`1 c)rn   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)rn   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)rn   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()rn   at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)rn   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()"
        }
    }
}

But both my database and my model looks correct, and from the exception itself it looks like its trying to call the database twice ?.

I am unsure of how to fix this issue

EF Model of database

Source: Visual Studio Questions

LEAVE A COMMENT