ASP MVC - Many to Many

I honestly searched for more than an hour for a satisfactory answer to this question. So it’s not that I didn’t find the answers, and not the ones that I feel are completely true. This may mean that I am looking for a silver bullet that does not exist.

In asp mvc with EF (the first code model), which includes many, many relationships, how to associate this relationship with checkboxes, and then elegantly distribute these changes in my database.

If the view only returns values ​​for the checked checkboxes, then I no longer know which values ​​were previously checked. I pulled back the original object again and then compare the two? It feels dirty, probably because I'm so used to letting EF magic control properties that have changed on the object.

I already have a dirty version that I'm not happy with.

[HttpPost] public ActionResult Edit(int id, FormCollection collection) { try { // TODO: Add insert logic here Program p = _programRep.GetByID(id); //manually update properties //change to model binding later EditPolicies(ref p, collection["SelectedPolicies"].ToString().Split(',')); _programRep.Save(p); return RedirectToAction("Index"); } catch { return View(); } } private void EditPolicies(ref Program c, string[] selectedvals) { //I could do comparison logic here int count = c.Policies.Count; for (int i = 0; i < count; i++) { c.Policies.Remove(c.Policies.ElementAt(0)); } for (int i = 0; i < selectedvals.Count(); i++) { Policy g = _policyRep.GetByID(int.Parse(selectedvals[i])); c.Policies.Add(g); } } 
+4
source share
1 answer

I'm not quite sure how you expect this to work, so I don’t know what you are looking for, but it is the right way and design.

There are many modeling examples. I wish I saved the link that I found, with a great example, where deleting an object from the collection simply means that there is no relationship, and not that the row should be deleted.

The only elegance I would add is something like:

  c.Policies.AddRange(_policyRep.GetByIDs(selectedvals[i])); 
+1
source

Source: https://habr.com/ru/post/1340092/


All Articles