Why is the HasLoadedOrAssignedValue property true?

Hey guys alright, here is the script:

VS 2008.NET 3.5 SP1, LINQ to SQL.

I have a Product Entity that has an ImageID field, so it is related to Image Entity. All of this is defined in schema and DBML.

Now, let's say I create a new Product object without an ImageID and save it to the database. At this point, the _Image field of the object has a HasLoadedOrAssignedValue of false, as it should be.

Now, when I go and retrieve this object from the database, without an image identifier, that is, ImageID is set to null, and the image property associated with it is also null, HasLoadedOrAssignedValue is true ... why ??

Now, when I try to set the ImageID property to a valid int, I get a ForeignKeyReferenceAlreadyHasValueException.

Now I know that people say: β€œOh, you must set the relationship property yourself, so Product.Image = someImage, not Product.ImageID = 2,” but I always set the ID field and it always works .... well , almost always

So my question is twofold:

  • Why is HasLoadedOrAssignedValue set to true if it should not
  • More importantly, why am I experiencing such inconsistent behavior. I know that you don’t always need to set the entity property directly, so why doesn't this work this time? And if it's a LINQ to SQL rule, then why can a rule be broken sometimes?

Hooray!

+4
source share
2 answers

The problem is that something is looking for the Image property and causing it to load - perhaps even a debugger.

Set a breakpoint in the Product.Image property and see which path calls it.

+2
source

So, I had the same problem today, and I don’t know if this will help anyone, but it turned out that in my LINQ Entity DBML file I had a relationship, say between Reviews and Users by UserID. The connection was named User1. When I loaded the form, I used this relation to set some information in the status bar. Unfortunately, I also had a list of users in a drop-down list elsewhere on the form. Therefore, when I tried to change the drop-down list, he knew that the data was already in use. As soon as I made a separate linq request for the form status bar, everything worked. I know this is the expected behavior, but it was rather unpleasant.

+1
source

All Articles