How to update multiple many to many relationship a

2019-07-19 18:17发布

问题:

I was wondering how could I update an entity with multiple many to many relationships. So if I had a car model with many connectors, inputvoltages, lenstypes and lightcolors. I want the user to be able to update all selections on one page and so when they submit the page all connectors, lights, etc are added or removed from the car. I was wondering if I should use a ViewModel and have each entity on the ViewModel or use the view-bag and pass a list of items. For when the user saves if someone else added or removed something from the car then the page will re-display itself. I'm using MVC5 with c# and Entity Framework 6

Example model

using System;
using System.Collections.Generic;

namespace Bob.Models
{
public partial class Car
 {
    public Car()
    {

        this.Connectors = new List<Connector>();
        this.InputVoltages = new List<InputVoltage>();
        this.LensTypes = new List<LensType>();
        this.LightColors = new List<LightColor>();

    }

    public int Id { get; set; }
    public string Name { get; set; }
    public byte[] RowVersion { get; set; }

}

    public ICollection<Connector> Connectors { get; set; }
    public ICollection<InputVoltage> InputVoltages { get; set; }
    public ICollection<LightType> LensTypes { get; set; }
    public ICollection<LightColor> LightColors { get; set; }

 }
}

Example Controller actions

    public ActionResult Edit(int id)
    {
        ViewBag.PossibleLightColors = lightcolorRepository.All;
         return View(carRepository.Find(id));
    }



    [HttpPost]
    public ActionResult Edit(Car car)
    {
        if (ModelState.IsValid) {
            carRepository.InsertOrUpdate(car);
            carRepository.Save();
            return RedirectToAction("Index");
        } else {
            ViewBag.PossibleLightColors = lightcolorRepository.All;
            return View();
        }
    }