How to update multiple many to many relationship and check for concurrency exceptions?

余生长醉 提交于 2019-12-11 02:54:24

问题


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

来源:https://stackoverflow.com/questions/19637369/how-to-update-multiple-many-to-many-relationship-and-check-for-concurrency-excep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!