1

当对象引用不存在的子记录时,我无法更新对象子记录。例如。表 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();

就像上下文试图删除不存在的颜色一样。我怎样才能解决这个问题?

4

3 回答 3

0

Nope, EF will always enforce constraints. The only way I could think of to do it would be to gen a second model that has no constraints, or has them removed that is used when you do not wish to enforce them.

But I think the correct answer here is to fix the violations. They should be removed or fixed in the database. Having a proper FK relationship in the first place with update and delete integrity actions would have prevented it in the first place.

于 2009-07-11T05:02:17.633 回答
0

不是 EF 强制执行约束而是数据库,这就是为什么您在尝试保存它时会收到错误。唯一的方法(据我所知)是确保孩子存在。您应该在数据库中的 Car 和 CarColor 表之间设置适当的外键约束。

于 2009-08-27T09:02:27.780 回答
0

好的哇——我只花了 40 分钟试图解决这个问题,但我不能......无论如何也不能直接解决。您似乎无法将实体框架设置为不强制执行关系约束。

您将不得不以某种方式下拉到“裸” sql。因此,在您的情况下,我会做一个 sql 视图,其中包含引用有效汽车颜色的汽车(执行子查询计数或类似的操作)并从那里加载具有有效颜色引用的汽车。

如果要为没有有效颜色的汽车设置颜色,请加载汽车但不使用 Include(),然后直接设置颜色对象。

于 2009-07-02T13:53:26.317 回答