0

I'm trying to update a foreign key relationship in EntityFramework 4 (with a microsoft sql server database) via a foreign key.

I load the object using .Single() and then try set to the the Object.ExampleId (The Example table is a reference table that corresponds to an enumeration in C#). Then I call SaveChanges() on the context.

Doing so works locally, but on production servers it fails and appears to hang. Using debug statements I've narrowed the hang down to the line where I actually set the Id.

I was able to fix the problem by loading the entire Example object and doing Object.Example = loadedExample instead of Object.ExampleId = exampleId.

My question is why is this the case? Other places I have been able to update relationships just by setting the Id. Is this a bad practice?

Evan
  • 5,925
  • 6
  • 33
  • 35
  • 1
    No it is not bad practice - once FK are exposed you should use them to set relations. There must be something else. In your dev. machine use SQL profiler and check that there is no lazy loading when you assign the Id. – Ladislav Mrnka May 23 '11 at 16:19

1 Answers1

1

The problem turned out to be that setting the FK id caused entity framework to load all the members of the foreign key relationship that had that id. On our staging and live servers the number of items in that relationship was a lot higher.

This caused the request to timeout and fail.

The solution was here: EF4 and undesired loading of related collection with AddObject

Community
  • 1
  • 1
Evan
  • 5,925
  • 6
  • 33
  • 35