public ActionResult ViewStatic() { string artId = HttpContext.Request["artId"]; JsonModel jsonData; if (!String.IsNullOrEmpty(artId) && Convert.ToInt32(artId) != 0) { int id = Convert.ToInt32(artId); #region ObjectStateManager 中已存在具有同一键的对象。ObjectStateManager 无法跟踪具有相同键的多个对象。 //知道为什么会报这个错了吧,,因为你先用的articleService.GetEntity(id);这是上下文中就已经有这个 //实体对象了,这时再根据它的Id新new一个对象,再去用articleService.update()当然会出错。因为你这儿的dbContext是线程内唯一的,所以会报“已存在具有同一键的对象”。 //ObjectStateManager 中已存在具有同一键的对象。ObjectStateManager 无法跟踪具有相同键的多个对象。 //Article artModelProxy = articleService.GetEntity(id); //Article realModel = new Article() //{ // Id = id, // ViewCount = artModelProxy.ViewCount + 1 //}; //BlogDb4ZynEntities dbContext = new Model.BlogDb4ZynEntities(); ////但是又出现了:修改实体时 对一个或多个实体的验证失败。加上关闭实体验证就好了 ////关闭EF实体验证 //dbContext.Configuration.ValidateOnSaveEnabled = false; //DbEntityEntry<Article> entry = dbContext.Entry<Article>(realModel); //entry.State = System.Data.EntityState.Unchanged; //entry.Property("ViewCount").IsModified = true; //int val = dbContext.SaveChanges(); #endregion BlogDb4ZynEntities dbContext = new Model.BlogDb4ZynEntities(); Article artModel = dbContext.Articles.Find(id); artModel.ViewCount += 1; int val = dbContext.SaveChanges(); jsonData = new JsonModel() { Status = 1, Message = "浏览量计数成功" }; } else { jsonData = new JsonModel() { Status = 0, Message = "没有参数" }; } return(Json(jsonData)); }
public ActionResult PraiseStatic() { string artId = HttpContext.Request["artId"]; JsonModel jsonData; if (!String.IsNullOrEmpty(artId) && Convert.ToInt32(artId) != 0) { int id = Convert.ToInt32(artId); BlogDb4ZynEntities dbContext = new Model.BlogDb4ZynEntities(); Article artModelProxy = dbContext.Articles.Find(id); artModelProxy.Digg += 1; int val = dbContext.SaveChanges(); if (val == 1) { jsonData = new JsonModel() { Status = 1, Message = "点赞计数成功" }; } else { jsonData = new JsonModel() { Status = 2, Message = "服务器繁忙,请稍后再赞" }; } } else { jsonData = new JsonModel() { Status = 0, Message = "没有参数" }; } return(Json(jsonData)); }