With LINQ to SQL you can’t change a foreign-key column directly on a tracked entity — the context owns the relationship. Setting the FK property yourself throws:
Operation is not valid due to the current state of the object
The wrong way
OrderRecord.customerId = 105;
Throws — the entity is attached and the context tracks the association, not the raw column.
The fix
Assign the related entity through the association instead:
OrderRecord.tblCustomer = db.tblCustomers.Single(t => t.customerID == 105);
No error — LINQ to SQL updates the FK for you when the change is submitted. (Fetching by a non-primary key like customerID here: use Single only when the column is unique, otherwise First.)
The same lesson in EF Core (2026)
Every ORM since has kept this rule in one form or another, because the root cause is tracked-entity state, not LINQ to SQL specifics:
- EF Core reference navigation:
order.Customer = context.Customers.Find(105);— EF fixes upOrderIdonSaveChanges(). Settingorder.CustomerId = 105on a tracked entity is actually fine in EF Core (FK properties are settable); the “not valid” class of errors appears when you mix tracked and detached state — e.g. assigning an entity that belongs to a different context instance, or re-attaching a detached graph. Attach the entity to the same context, or set the FK instead. - The modern trade-off: setting the FK value (
CustomerId = 105) is cheaper — no query — and is the idiomatic choice when you only have an id. Set the navigation when you already have the entity in hand or want the related object loaded. - Detached scenarios (web apps): with a disconnected entity, either
Attach+ set the FK, or fetch-then-update in one context. The error message never says which state is wrong, so the mental model — “who owns this entity’s state, and is it in this context?” — is the durable takeaway.