我有多对多的关系黑白司机和车辆实体,在创建驱动程序时,可以将许多车辆分配给驱动程序,它工作正常,但是当我想编辑和更新记录时,我得到了null车辆集合,
以下是我的模特:
public class Driver {
public int driverId {get;set;}
public string Name {get;set;}
public virtual ICollection<Vehicle> Vehicles {get;set;}
}
public class Vehicle {
public int Vehicle_Id {get;set;}
public string Vehicle_Type_Name {get;set;}
public virtual ICollection<Driver> Drivers {get;set;}
}
我在这里定义了这段关系:
modelBuilder
.Entity<Driver>()
.HasMany<Vehicle>(d => d.Vehicles)
.WithMany(d => d.Drivers).Map(
cs =>
{
cs.MapLeftKey("DriverId")
.MapRightKey("VehicleId")
.ToTable("DriversVehicles");
});
我的驱动程序View Model
public class DriverViewModel
{
public DriverViewModel()
{
SelectedVehicles=new List<int>();
VehicleList = new List<Vehicle>();
}
public Driver driver { get; set; }
public List<int> SelectedVehicles { get; set; }
public List<Vehicle> VehicleList { get; set; }
}
这里是驱动程序Edit()Controller Action:
public ActionResult Edit(int id = 0)
{
DriverViewModel DriverVm = new DriverViewModel();
var list = db.vehicles.Select(
v => new { v.Vehicle_Id,v.Vehicle_Type_Name }).ToList();
DriverVm.driver = db.drivers.Find(id);
foreach (var item in list)
{
DriverVm.VehicleList.Add(new Vehicle { Vehicle_Id = item.Vehicle_Id, Vehicle_Type_Name = item.Vehicle_Type_Name });
}
foreach (var item in DriverVm.driver.Vehicles)
{
DriverVm.SelectedVehicles.Add(item.Vehicle_Id);
}
return View(DriverVm);
}
这是编辑的POST动作:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(DriverViewModel driverVm)
{
var list = db.vehicles.Select(v =>
new { v.Vehicle_Id, v.Vehicle_Type_Name }).ToList();
foreach (var item in list)
{
driverVm.VehicleList.Add(
new Vehicle {
Vehicle_Id = item.Vehicle_Id,
Vehicle_Type_Name = item.Vehicle_Type_Name
});
}
if (ModelState.IsValid)
{
db.Entry(driverVm.driver).State = EntityState.Modified;
db.SaveChanges();
List<Vehicle> vhcls = new List<Vehicle>();
Driver driver = db.drivers.Find(driverVm.driver.driverId);
vhcls = driver.Vehicles.ToList();
foreach (Vehicle veh in vhcls)
{
driver.Vehicles.Remove(veh);
}
db.SaveChanges();
foreach (var item in driverVm.SelectedVehicles)
{
Vehicle vehicle = db.vehicles.Find(item);
driverVm.driver.Vehicles.Add(vehicle);
}
db.SaveChanges();
TempData["DriverSuccess"] = "1";
return RedirectToAction("Edit");
}
else
{
ViewBag.DriverError = "1";
}
return View(driverVm);
}
实际问题在于:
Driver driver = db.drivers.Find(driverVm.driver.driverId);
vhcls = driver.Vehicles.ToList();
foreach (Vehicle veh in vhcls)
{
driver.Vehicles.Remove(veh);
}
db.SaveChanges()
列表&#34; vhcls&#34;在上面的代码中是空的,它应该包含与驱动程序相关的车辆,但是&#34; driver&#34;对象包含&#34; driverVm.driver.Vehicles&#34;中的Null集合。我没有使用相关的车辆,而是徘徊不好但无法找到解决方案。请帮助......
答案 0 :(得分:1)
仅使用find
将不包含相关实体。驱动程序很可能包含正确的实体,但Vehicle集合是空的。
尝试使用Include
确保包含相关实体,并FirstOrDefault
模拟Find
的结果。
Driver driver = db.drivers
.Include(d => d.Vehicles)
.FirstOrDefault(d => d.Id == driverVm.driver.driverId);
vhcls = driver.Vehicles.ToList();
编辑:我最初错过了您已经在使用延迟加载,所以我稍微调整了答案。