1

Is it possible to update/remove multiples entities, for example

[HttpPost, ActionName("removeresponsible")]
public ActionResult removeresponsibleaction(Responsible modelo)
{
    Responsible responsible = db.Responsibles.Single(x => x.responsible_id == modelo.responsible_id);
    db.Responsibles.Remove(responsible);
    db.SaveChanges();
    ViewBag.responsible = db.Responsibles.ToList();
    return View("responsiblemanager");
}

This code works with one single responsible with an unique id, but how can I do it if there are many responsible with the same id? For example, I know that with SQL it would be something like this "delete from table where responsible_id=3".

2 Answers 2

1

If you are using Entity Framework 6 you can use RemoveRange method:

var responsibles = db.Responsibles.Where(x => x.responsible_id == modelo.responsible_id).ToList();
db.Responsibles.RemoveRange(responsibles);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your quickly answer, i tried it and it worked perfectly
0

If you aren't using EF 6, you will have to loop through your list of models, and delete each one separately.

e.g.

[HttpPost, ActionName("removeresponsible")]
public ActionResult removeresponsibleaction(IEnumerable<Responsible> models)
{
    foreach(var model in models)
    {
        Responsible responsible = db.Responsibles.Single(x => x.responsible_id == model.responsible_id);
        db.Responsibles.Remove(responsible);
    }
    db.SaveChanges();
    ViewBag.responsible = db.Responsibles.ToList();
    return View("responsiblemanager");
}

1 Comment

thanks for your answer, i tried it on EF 5.0.0.0 too and worked, it's easier in EF 6 but it's also helpful to know how to when there is no access to EF 6

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.