I'm currently working on a C# project which uses Entity Framework DB First to connect to MSSQL Database.
Most of the DB operations work well. However there still are some table-columns, which are foreign keys, that cannot be updated.
Let's say, we have table: Truck with 2 foreign key fields: start_plan_id, plan_id pointing to another table: Plan, with 2 Navigation Properties in EF Model: Truck.Start_Plan, Truck.Plan
Now when I run test code as follows, to update a record:
// 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);
The EF logs showed that the old values were sent in UPDATE command:
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)
Where plan_id (@3) should be the new value: 'TC-015000'
Also the operation ended with Exception:
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.
I've tried searching but did not found anything resembling my case. Any idea please?
Best Regards, Chakrit W.