【问题标题】:System.Data.Entity.Infrastructure.DbUpdateConcurrencyException. Store update, insert, or delete statement affected an unexpected number of rows (0)System.Data.Entity.Infrastructure.DbUpdateConcurrencyException。存储更新、插入或删除语句影响了意外数量的行 (0)
【发布时间】:2016-07-04 08:48:10
【问题描述】:

模型 这些是模型类,我正在使用实体框架。我正在使用这些模型来实现级联下拉列表。

  public class League
    {
        public int Id { get; set; }
        public string League1 { get; set; }
        public string Icon { get; set; }

        public virtual ICollection<LeagueDivision> LeagueDivisions { get; set; }
    }

  public class LeagueDivision
    {
        public int Id { get; set; }
        public Nullable<int> LeagueId { get; set; }
        public string Name { get; set; }
        public string Icon { get; set; }

        public virtual League League { get; set; }
    }  

  public partial class CalculatorPrice
    {
        public int Id { get; set; }
        public int LeagueId { get; set; }
        public int LeagueDivisionId { get; set; }
        public Nullable<decimal> Price { get; set; }
    } 

 public class ViewModelForHostBooster
    {
        [Required(ErrorMessage = "Please enter price")]
        [Display(Name = "Price")]
        public decimal Price { get; set; }       

        [Required(ErrorMessage = "Please select a league")]
        [Display(Name = "League")]

        public int? SelectedLeague { get; set; }
        [Required(ErrorMessage = "Please select a league division")]
        [Display(Name = "League Division")]

        public int? SelectedLeagueDivision { get; set; }

        public SelectList LeagueList { get; set; }
        public SelectList LeagueDivisionList { get; set; }    

    }

控制器/动作 在 HttpGet 中,我刚刚填充了级联下拉列表并且工作正常,现在我正在为此实现 Httppost。我想根据从下拉列表中选择的列表项存储 price,如果 price 已经存在,那么我想更新它。第一次我可以成功添加 price 但第二次尝试更新它时我得到 System.Data.Entity.Infrastructure.DbUpdateConcurrencyException 请任何人指导我如何处理这个。

[HttpPost]
 public ActionResult IndexDropDown(ViewModelForHostBooster model)
    {
        if (!ModelState.IsValid)
        {
            ConfigureViewModel(model);
            return View(model);
        }
        else
        {
            HostBoostersDBEntities2 db = new HostBoostersDBEntities2();
            CalculatorPrice calculatePrice = new CalculatorPrice();
             var  calculatePriceExistsOrNot =  db.CalculatorPrices
                .Where(x => x.LeagueId == model.SelectedLeague
                    &&
                    x.LeagueDivisionId == model.SelectedLeagueDivision).ToList();
             if (calculatePriceExistsOrNot.Count > 0)
            {

                calculatePrice.LeagueId = (int)model.SelectedLeague;
                calculatePrice.LeagueDivisionId = (int)model.SelectedLeagueDivision;
                calculatePrice.Price = model.Price;
                db.Entry(calculatePrice).State = EntityState.Modified;

异常发生在 db.SaveChanges(); 行 “System.Data.Entity.Infrastructure.DbUpdateConcurrencyException”发生在 EntityFramework.dll 中,但未在用户代码中处理。 附加信息:存储更新、插入或删除语句影响了意外数量的行 (0)。自加载实体后,实体可能已被修改或删除。刷新 ObjectStateManager 条目。

                db.SaveChanges();
            }
            else
            {
                calculatePrice.LeagueId = (int)model.SelectedLeague;
                calculatePrice.LeagueDivisionId = (int)model.SelectedLeagueDivision;
                calculatePrice.Price = model.Price;
                db.CalculatorPrices.Add(calculatePrice);
                db.SaveChanges();
            }


        }
        ConfigureViewModel(model);
        return View(model);
    }

查看

  @using (Html.BeginForm("IndexDropDown", "DropDown", FormMethod.Post,
                                      new { enctype = "multipart/form-data" }))
{
    <div>
        @Html.LabelFor(m => m.Price, new { @class ="control-lebel"})
        @Html.TextBoxFor(m => m.Price, new { @class = "form-control"})
        @Html.ValidationMessageFor(m => m.Price)
    </div>

    <div>
        @Html.LabelFor(m => m.SelectedLeague ,new { @class ="control-lebel"})
        @Html.DropDownListFor(m => m.SelectedLeague, Model.LeagueList, new { @class = "form-control"})
        @Html.ValidationMessageFor(m => m.SelectedLeague)
    </div>
    <div>
        @Html.LabelFor(m => m.SelectedLeagueDivision ,new { @class ="control-lebel"})
        @Html.DropDownListFor(m => m.SelectedLeagueDivision, Model.LeagueDivisionList, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.SelectedLeagueDivision)
    </div>
    <input type="submit" value="save" />
}

【问题讨论】:

  • @Stephen Muecke 在互联网上搜索此问题的解决方案后,我了解到如果我们想要更新任何实体,我们不需要创建该实体的新对象。我们只需要将它传递给 db.Entry(model).State = EntityState.Modified;但我正在创建calculatorPrice 的新实例。问题在这里,我在参数中传递 ViewModelForHostBoosters 并想要更新calculatorPrice 表。你能指导我如何管理我的场景吗?

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


【解决方案1】:
[HttpPost]
 public ActionResult IndexDropDown(ViewModelForHostBooster model)
    {
        if (!ModelState.IsValid)
        {
            ConfigureViewModel(model);
            return View(model);
        }
        else
        {
            HostBoostersDBEntities2 db = new HostBoostersDBEntities2();
            CalculatorPrice calculatePrice  =  db.CalculatorPrices
                .Where(x => x.LeagueId == model.SelectedLeague
                    &&
                    x.LeagueDivisionId == model.SelectedLeagueDivision).FirstOrDefault();
             if (calculatePrice != null)
            {
                calculatePrice.LeagueId = (int)model.SelectedLeague;
                calculatePrice.LeagueDivisionId = (int)model.SelectedLeagueDivision;
                calculatePrice.Price = model.Price;
                //db.Entry(calculatePrice).State = EntityState.Modified;
                db.SaveChanges();
            }
            else
            {
                calculatePrice = new CalculatorPrice();
                calculatePrice.LeagueId = (int)model.SelectedLeague;
                calculatePrice.LeagueDivisionId = (int)model.SelectedLeagueDivision;
                calculatePrice.Price = model.Price;
                db.CalculatorPrices.Add(calculatePrice);
                db.SaveChanges();
            }


        }
        ConfigureViewModel(model);
        return View(model);
    }

【讨论】:

  • 谢谢你,亲爱的,它工作正常。我从您的指导中学到了很多东西。它正在成功更新,但是当我添加新价格时,它会抛出空异常,因为我们没有创建 CalculatorPrice 的新对象来添加新条目,所以我更改了代码...我想要问为什么我们不需要 db.Entry(calculatePrice).State = EntityState.Modified;在更新期间...等待阅读您的话..谢谢
  • @Sulaiman 因为当您从数据库中获取 CalculatorPrice 后,EF 会继续观察并了解其属性是否发生变化,因此 EF 本身会将其状态更改为已修改
  • @Arvin 我明白了。谢谢
  • @Arvin......亲爱的我已经投票了,但弹出一条消息“感谢投票记录,但谁的声望点低于 15,他们的投票无法发布”。 .....我很抱歉,但你的回答太解释了。正是因为你的回答,我的问题才解决了
  • 因为一大段代码而被否决
【解决方案2】:

我们发现了同样的错误,因为我们在插入和删除时使用了两个触发器。 我们有删除触发器然后问题是解决我们的问题。

【讨论】:

    【解决方案3】:

    Id 有问题。

    当我从一个视图重定向到另一个视图时,Id 不知何故消失了

    所以我在方法中捕获了正确的 Id,然后将用户重定向到编辑方法。 为了指定,在第一个视图(“索引”)中,我使用 ActionLink 将用户重定向到捕获 Id 的方法,然后在捕获正确的 Id 后,将用户重定向到编辑方法。这可能不是最好的解决方案,但它对我有用。

    索引视图

    @Html.ActionLink("Capture Id", "CauptureId", new { Model.Id }, null)
    

    获取 ID

    public ActionResult CauptureId(int? id)
            {
                Class nameOfClass = context.dbRow.Where(i => i.Id == id).FirstOrDefault();
    
                return RedirectToAction("Edit", new { id = editIngredienser.Id});
            }
    

    编辑方法

    public ActionResult Edit(int? id)
            {
                if (id == null)
                {
                    return RedirectToAction("Index");
                }
                Class nameOfClass = db.dbRow.Find(id);
                return View(nameOfClass);
            }
            [HttpPost]
            public ActionResult Edit(Class nameOfClass)
            {
    
                db.Entry(nameofClass).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
         
                return RedirectToAction("Index");
            }
    

    结论

    问题我遇到的问题是我试图用一个空的 Id 更新数据库中的一行,因为它消失了。

    解决方案:我使用了一种方法来捕获正确的 Id,以便能够更新数据库中的正确行。

    正如我上面提到的,到目前为止,这并不是最佳实践。但它对我来说是一个临时解决方案。我希望你能找到它的一些用途。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-01
      相关资源
      最近更新 更多