实体框架数据库优先不更新外键列

时间:2019-03-02 11:32:23

标签: c# database entity-framework foreign-keys

我目前正在研究一个使用Entity Framework DB First连接到MSSQL数据库的C#项目。

大多数数据库操作都能正常工作。但是,仍然有一些表列是外键,无法更新。

比方说,我们有一个表:具有2个外键字段的卡车:start_plan_id,plan_id指向另一个表:Plan,在EF模型中具有2个导航属性:Truck.Start_Plan,Truck.Plan

现在,当我按如下方式运行测试代码时,将更新记录:

// planID2 = "TC-015000"

truck.Plan = null;
truck.plan_id = planID2;
// ...

db.Entry(truck).State = EntityState.Modified;
// Here, truck.Plan == null and truck.plan_id == "TC-015000"
// and db.Entry(truck) entity states are seemingly correct

success = (db.SaveChanges() >= 1);

EF日志显示旧值是通过UPDATE命令发送的:

UPDATE [dbo].[Truck]
SET [type] = @0, [car_brand] = @1, [start_plan_id] = @2, [plan_id] = @3, [is_active] = @4
WHERE ([Car_ID] = @5)

-- @0: 'Trailer' (Type = String, Size = 255)

-- @1: 'HINO' (Type = String, Size = 255)

-- @2: 'TC-010000' (Type = String, Size = 255)

-- @3: 'TC-010000' (Type = String, Size = 255)

-- @4: 'True' (Type = Boolean)

-- @5: '139' (Type = Int32)

其中plan_id(@ 3)应为新值:“ TC-015000”

操作也以异常结束:

The changes to the database were committed successfully,
 but an error occurred while updating the object context.
 The ObjectContext might be in an inconsistent state.
Inner exception message: A referential integrity constraint violation occurred:
 The property value(s) of 'Plan.ID' on one end of a relationship
 do not match the property value(s) of 'Truck.plan_id' on the other end.

我尝试搜索,但没有发现与我的情况相似的内容。 有什么想法吗?

最好的问候, Chakrit W。

2 个答案:

答案 0 :(得分:0)

请查看以下讨论,我想您可以在此处找到答案:

Unable to update Foreign Key in Entity Framework 6

答案 1 :(得分:0)

感谢CoLiNaDENavid Rsh的其他信息,我进行了更多测试,发现添加以下行: db.ChangeTracker.DetectChanges(); 之前 db.SaveChanges();

至少对以下两种更新方法有用:

  1. 先设置truck.Plan = db.Plan.Find(planID2);,然后再设置truck.plan_id = truck.Plan.ID;

  2. 先设置truck.Plan = null;,然后再设置truck.plan_id = planID2;

我很快会再检查其他情况。

最好的问候,