数据库更新

时间:2017-09-16 11:29:25

标签: c# mysql sql asp.net entity-framework

我对我正在进行的API有这种投票方法(我确信还有很大的改进空间,所有建议都表示赞赏)。

我收到此错误:

“存储更新,插入或删除语句影响了意外的行数(0)。实体可能在加载实体后被修改或删除。有关理解和处理乐观的信息,请参阅http://go.microsoft.com/fwlink/?LinkId=472540并发异常。“ ExceptionType: “System.Data.Entity.Core.OptimisticConcurrencyException”

但一切似乎都运转正常

我添加了一个新的投票对象,投票用户连接到它。并使用新的nr票更新帖子..

有人可以解释这里出了什么问题吗?或许建议解决方案

    [HttpGet]
    [Authorize]
    [Route("api/vote")]
    [SwaggerResponse(HttpStatusCode.OK, Type = typeof(Post))]

    public IHttpActionResult Vote(string image_id, bool upVote)
    {
        // http://api.badgag.com/api/up/?image=123&upVote=true

        User user = new User(ClaimsPrincipal.Current.Claims);
        if (user != null)
        {
            telemetry.Context.User.Id = user.user_id;
        }

        Post post = (from p in db.Posts where p.image.id == image_id select p).FirstOrDefault();

        // find post with image_id
        if (post == null)
        {
            // string message = "Could not find image";
            string message = "2";
            System.Diagnostics.Trace.TraceWarning(message);
            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, message));
        }

        if (post.creator.user_id == user.user_id)
        {
            // string message = "User cannot vote on his own post";
            string message = "3";
            System.Diagnostics.Trace.TraceWarning(message);
            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, message));
        }

        // TODO: find a faster way to look this up!
        foreach (Vote v in post.votes)
        {
            if (v.user.user_id == user.user_id)
            {
                // string message = "User already voted on this post";
                string message = "4";
                System.Diagnostics.Trace.TraceWarning(message);
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, message));
            }
        }

        // add new vote
        Vote vote = new Vote();

        // if user does exist in db, add that object
        // if not, use new user object generated from claims
        vote.user = (from u in db.Users where u.user_id == user.user_id select u).FirstOrDefault();
        if (vote.user == null)
        {
            vote.user = user;
        }

        vote.upVote = upVote;
        vote.datetime = DateTime.Now;
        post.votes.Add(vote);

        // calc rating
        post.rating = new Rating();
        post.rating.datetime = post.image.datetime;
        post.rating.up = post.votes.Count(v => v.upVote == true);
        post.rating.down = post.votes.Count(v => v.upVote == false);
        post.rating.calc();

        // ERROR on saveChanges()
        /*
            "Store update, insert, or delete statement affected an unexpected number of rows (0). 
            Entities may have been modified or deleted since entities were loaded. 
            See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions."

            ExceptionType: "System.Data.Entity.Core.OptimisticConcurrencyException"
         */

        // update post in DB
        db.SaveChanges();

        // remove sensitive info from Post before returning
        post.creator.email = "removed";
        post.creator.gender = "removed";
        post.creator.locale = "removed";
        post.creator.nickname = "removed";
        post.creator.picture = "removed";
        post.image.deletehash = "removed";
        post.votes.Clear();

        return Json(post);
        // return Json("user: " + user.user_id + " votes up image id: " + image);
    }

PS。如果您对测试感兴趣,则来自badgag.com。上传帖子并投票:)

编辑: 完整的错误消息

{Message: "An error has occurred.", ExceptionMessage: "An error occurred while saving entities that do no…entity types. See the InnerException for details.", ExceptionType: "System.Data.Entity.Infrastructure.DbUpdateException", StackTrace: "   at System.Data.Entity.Internal.InternalContext.…tpControllerDispatcher.<SendAsync>d__1.MoveNext()", InnerException: {…}}
ExceptionMessage
:
"An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details."
ExceptionType
:
"System.Data.Entity.Infrastructure.DbUpdateException"
InnerException
:
ExceptionMessage
:
"Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions."
ExceptionType
:
"System.Data.Entity.Core.OptimisticConcurrencyException"
Message
:
"An error has occurred."
StackTrace
:
"   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.ValidateRowsAffected(Int64 rowsAffected, UpdateCommand source)
↵   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
↵   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
↵   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
↵   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
↵   at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
↵   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
↵   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
↵   at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
↵   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
↵   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
↵   at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
↵   at System.Data.Entity.Internal.InternalContext.SaveChanges()"
__proto__
:
Object
Message
:
"An error has occurred."
StackTrace
:
"   at System.Data.Entity.Internal.InternalContext.SaveChanges()
↵   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
↵   at System.Data.Entity.DbContext.SaveChanges()
↵   at Api.Controllers.PostController.Vote(String image_id, Boolean upVote) in C:\git\secureapi\Api\Controllers\PostController.cs:line 95
↵   at lambda_method(Closure , Object , Object[] )
↵   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
↵   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
↵   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
↵--- End of stack trace from previous location where exception was thrown ---
↵   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
↵   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
↵   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
↵--- End of stack trace from previous location where exception was thrown ---
↵   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
↵   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
↵   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
↵--- End of stack trace from previous location where exception was thrown ---
↵   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
↵   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
↵   at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()
↵--- End of stack trace from previous location where exception was thrown ---
↵   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
↵   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
↵   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
__proto__
:
Object

0 个答案:

没有答案