4

Models These are model classes and I am using Entity Framework. I am using these models to implement cascaded drop down list.

  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; }    

    }

Controller/Actions In HttpGet I just populated cascaded dropdown list and working fine now I am implementing Httppost for this. I want to store price depending upon selected list items from dropdown list and if the price already exists then I want to update it. First time I can add price successfully but second time when I am trying to update it I am getting System.Data.Entity.Infrastructure.DbUpdateConcurrencyException Please can anybody guide me how to handle this.

[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;

Exception occurs here in line db.SaveChanges(); 'System.Data.Entity.Infrastructure.DbUpdateConcurrencyException' occurred in EntityFramework.dll but was not handled in user code. Additional information: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

                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);
    }

View

  @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" />
}
1
  • @Stephen Muecke After searching solution to this problem on internet I have learned that if we want to update any entity we need no to crate new object of that entity. we just need to pass it to db.Entry(model).State = EntityState.Modified; but I am creating new instance of calculatorPrice. The problem is here I am passing ViewModelForHostBoosters in argument and want to update calculatorPrice table. can you please guide how I can manage my scenario. Commented Jul 4, 2016 at 11:37

3 Answers 3

2
[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);
    }
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you you much dear it is working fine. I have learned a lot from your guidance.. It is updating successfully but when I am adding new price then it is throwing null exception because we did not create new object of CalculatorPrice to add new entry so I change the code...I want to ask why we need not db.Entry(calculatePrice).State = EntityState.Modified; during updating...waiting to read your words..Thanks
@Sulaiman because when after you get CalculatorPrice from database, EF keep watching it and understand if its properties changed, so EF itself change its State to Modified
@ Arvin I got it. Thanks
@Arvin......dear I have voted but a message poped up that "thanks vote recorded but who has less than 15 reputation point their votes can not be published". .....I am sorry for that but your answer was too explainatory. My problem was solved just because of your answer
Downvoted because of a chunk of code without any clarification
|
0

We have found same error because we have used two trigger on insert and delete. we have delete trigger then issue is resolve our side.

Comments

0

Had an issue with the Id.

As I got redirected from one view to another, the Id somehow disappeared.

So I captured the correct Id in a method and then redirected the user to the edit method. To specify, in the first view ("Index"), I use an ActionLink to redirect the user to a method that captures the Id, then, after capturing the correct Id, the user is redirected to the edit method. This may be not the best solution, but it worked for me.

Index view

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

Capturing the Id

public ActionResult CauptureId(int? id)
        {
            Class nameOfClass = context.dbRow.Where(i => i.Id == id).FirstOrDefault();

            return RedirectToAction("Edit", new { id = editIngredienser.Id});
        }

Edit method

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");
        }

Conclusion

Problem: The problem that I had was that I tried to update a row in the DB with an Id that was null because it disappeared.

Solution: I used a method to capture the correct Id to be able to update a correct row in my database.

As I mentioned above, this Isn't most likely, by far, the best practice. But it worked for me as a temporary solution. I hope you can find some use of it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.