1

I'm trying to update multiple objects that exist in database and save new objects, but it doesnt work?

Here is my code:

    [HttpPost]
    public ActionResult Edit(MasterModel Model)
    {
        DBEntities db = new DBEntities();
        var reloadView = true;
        for(int i = 0 ;i< Model.Emails.Count(); i++)
        {
            if(Model.Emails[i].ID > 0 )
            {
                var id = Model.Emails[i].ID;
                var email = db.EMAIL.Single(e=> e.ID == id);
                if(TryValidateModel(Model.Emails[i], "Emails[" +i.ToString() + "]"))
                {
                    TryUpdateModel(email, "Emails[" + i.ToString() + "]");
                    reloadView = false;
                }
                else
                {
                    reloadView = true;
                }

            }
            else
            {
                if(TryValidateModel(Model.Emails[i], "Emails[" + i.ToString() + "]"))
                {
                    db.AddToEMAIL(Model.Emails[i]);
                    reloadView = false;
                }
                else
                {
                    reloadView = true;
                }
            }
        }

        if(reloadView)
        {
            return View(Model);
        }
        else
        {
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }

if after TryUpdateModel I do db.SaveChanges(); i get a System.Data.UpdateException with referential integrity

And if I let my code like in the example it just doesn't update! :S

Oh yeah, I've also tried UpdateModel() instead.

Any suggestions?

Thanks in advance!

Cheers

jperez
  • 1,020
  • 1
  • 10
  • 25

1 Answers1

0

The usual workflow for update an object is:

1) Load old object (using id) 2) Change properties 3) SaveChanges

ADIMO
  • 1,107
  • 12
  • 24
  • Thanks for your answer but it doesnt have any positive effect on my question. If you look to my code im getting from db im updating model and im saving changes. Or are you seeing something i dont see? – jperez Nov 03 '11 at 17:30
  • Hi I see that your code implement also insert (Model.Emails[i].ID > 0) and I dont understand why if you post edit action. – ADIMO Nov 04 '11 at 08:44