当对象引用不存在的子记录时,我无法更新对象子记录。例如。表 Car 和 CarColor 有关系。Car.CarColorId >> CarColor.CarColorId 如果我像这样加载带有颜色记录的汽车
var result = from x in database.Car.Include("CarColor")
where x.CarId = 5
select x;
我将取回 Car 对象,它是 Color 对象。现在假设前一段时间 CarColor 已被删除,但有问题的 Car 记录仍包含 CarColorId 值。因此,当我运行查询时,Color 对象为 null,因为 CarColor 记录不存在。我的问题是,当我附加另一个确实存在的 Color 对象时,我得到了一个商店更新,保存时插入错误。
Car.Color = newColor
Database.SaveChanges();
就像上下文试图删除不存在的颜色一样。我怎样才能解决这个问题?