0

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.

Chakrit W
  • 322
  • 3
  • 11
  • I think you shouldn't set the plan_id and start_plan_id when you are using EF. Just get the Plan Object from the context and set it to Truck.Plan/Truck.Start_Plan Navigation Properties. – CoLiNaDE Mar 02 '19 at 11:56
  • I've just tried setting `truck.Plan = db.Plan.Find(planID2);` without modifying truck.planID. The result was the same (UPDATE statement parameters were set to old values) – Chakrit W Mar 02 '19 at 15:23

1 Answers1

0

Thanks for additional info from CoLiNaDE and Navid Rsh, I've tested some more and found out that adding this line: db.ChangeTracker.DetectChanges(); before db.SaveChanges();

does the trick for at least these 2 update methods:

  1. Setting truck.Plan = db.Plan.Find(planID2); then truck.plan_id = truck.Plan.ID;

  2. Setting truck.Plan = null; then truck.plan_id = planID2;

I'd re-check with other cases soon.

Best Regards,

Chakrit W
  • 322
  • 3
  • 11