【发布时间】:2019-03-02 11:32:23
【问题描述】:
我目前正在开发一个使用 Entity Framework DB First 连接到 MSSQL 数据库的 C# 项目。
大多数数据库操作运行良好。但是,仍然有一些表列,它们是外键,无法更新。
假设我们有一个表:Truck 有 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.
【问题讨论】:
-
我认为你在使用EF的时候不应该设置plan_id和start_plan_id。只需从上下文中获取计划对象并将其设置为 Truck.Plan/Truck.Start_Plan Navigation Properties。
-
我刚刚尝试设置
truck.Plan = db.Plan.Find(planID2);而不修改 Truck.planID。结果是一样的(UPDATE语句参数设置为旧值)
标签: c# database entity-framework foreign-keys