SaveChanges在JsonResult方法上不起作用(更新信息)

时间:2019-04-08 17:15:24

标签: c# asp.net entity-framework jsonresult

问题基本上是Save changes方法不起作用(更新),该方法应该接收3个参数,即项ID,用户ID和包含来自UI的更新信息的对象,但是代码似乎有问题因为saveChanges()方法不起作用。

这是我的代码:

[HttpPost]
    [AllowAnonymous]
    public JsonResult UpdatePersonalData(int ItemId, int UserId, CND_PersonalData Item)
    {
        try
        {
            if (ModelState.IsValid)
            {
                using (var context = new DexusEntities())
                {
                    CND_PersonalData PersonalData = context.CND_PersonalData.Where(d => d.Id == ItemId && d.UserId == UserId).SingleOrDefault();
                    if (PersonalData == null)
                    {
                        /// Display bad request
                        /// User does not exist and/or is not activated
                        List<RootObject> rootObj = new List<RootObject>();
                        rootObj.Add(new RootObject
                        {
                            msg = "User/Item not found in our DB",
                            code = "error_07"
                        });
                        HttpContext.Response.StatusCode = 404;
                        HttpContext.Response.TrySkipIisCustomErrors = true;
                        JsonRes.Message = rootObj;
                        return Json(JsonRes, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        PersonalData = Item;
                        context.SaveChanges();
                        context.ChangeTracker.DetectChanges();
                        List<RootObject> rootObj = new List<RootObject>();
                        rootObj.Add(new RootObject
                        {
                            msg = "Information stored/updated successfully",
                            code = "success_05"
                        });
                        HttpContext.Response.StatusCode = 200;
                        JsonRes.Message = rootObj;
                        return Json(JsonRes, JsonRequestBehavior.AllowGet);
                    }
                }
            }
            else
            {
                List<RootObject> rootObj = new List<RootObject>();
                JsonRes.Issue = "The model is not correct";
                rootObj.Add(new RootObject
                {
                    msg = "Model is not valid",
                    code = "error_03"
                });
                HttpContext.Response.StatusCode = 403;
                HttpContext.Response.TrySkipIisCustomErrors = true;// Avoid issues in the HTTP methods
                JsonRes.Message = rootObj;
                return Json(JsonRes, JsonRequestBehavior.AllowGet);
            }
        }
        catch (Exception ex)
        {
            string err = ex.ToString();
            List<RootObject> rootObj = new List<RootObject>();
            JsonRes.Issue = err;
            rootObj.Add(new RootObject
            {
                msg = "Conflict with method, see issue description.",
                code = "error_08"
            });
            HttpContext.Response.StatusCode = 400;// Bad request
            HttpContext.Response.TrySkipIisCustomErrors = true;
            JsonRes.Message = rootObj;
            return Json(JsonRes, JsonRequestBehavior.AllowGet);
        }
    }

我的代码有什么问题? 预先感谢。

1 个答案:

答案 0 :(得分:0)

如我所见,您没有将项目添加到DbSet中,而是在之后调用SaveChanges:

添加项目时,应将其放入DbSet

context.CND_PersonalData.Add(item);
context.SaveChanges();

要更新时,只需在更新加载的对象后调用SaveChanges

    var PersonalData= context.CND_PersonalData.Where(d => d.Id == ItemId && d.UserId == UserId).SingleOrDefault();
 PersonalData.Name = item.Name;
PersonalData.Title = item.Title;
    context.SaveChanges();

您不能仅将传递的对象分配给从数据库获得的实体,还需要更改属性。如果像以前那样进行操作,则不会更改已加载对象中的值。因此,当您调用SaveChanges时,什么都不会改变。您需要一个一个地更改属性。

如果您不想这样做,则可以通过在上下文上使用Attach方法将项目附加到数据库中。

context.Attach(item);
context.SaveChanges();

但是要小心,因为如果在检查项目是否为空之前加载和跟踪与您具有相同ID的项目,则该操作:

CND_PersonalData PersonalData = context.CND_PersonalData.Where(d => d.Id == ItemId && d.UserId == UserId).SingleOrDefault();
                    if (PersonalData == null)
                    {

然后,由于上下文已经在跟踪具有相同ID的项目,因此在保存过程中将出现错误,因此您可以删除该检查并仅检查它是否存在:

if (context.CND_PersonalData.Any(d => d.Id == ItemId && d.UserId == UserId))
   {

然后执行您的代码