Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is HasLoadedOrAssignedValue Property set to true?

Here is the scenario:

  • VS 2008 .NET
  • 3.5 SP1
  • LINQ to SQL

I have a Product Entity, which has an ImageID field, so it has a relationship with the Image Entity. This is all defined in the schema and DBML.

Now, say I create a new Product entity, without a ImageID, and save it to the DB. At this point, the _Image field of the Entity has HasLoadedOrAssignedValue set to false, as it should.

Now, when I go and retrieve that entity from the DB, without an ImageID, i.e ImageID is set to null, and the Image Entity attached to it is also set to null, HasLoadedOrAssignedValue is set to true. Why?

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

Now, I know that people say, "oh, you have to set the relationship property itself, 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:

  1. Why is the HasLoadedOrAssignedValue set to true when it shouldn't?
  2. More importantly, why am I experiencing this incoherent behavior. I know that you don't always have to set the entity property directly, so why is it not working this time? And if this is a LINQ to SQL rule, then why can the rule sometimes be broken?
like image 539
andy Avatar asked Jul 14 '09 07:07

andy


2 Answers

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

Set a breakpoint in the Product.Image property and see what path is causing it.

like image 144
DamienG Avatar answered Sep 28 '22 08:09

DamienG


So, I had this 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, let's say between Reviews and Users by UserID. The relationship was named User1. When I loaded the form, I used that relationship to set some information in a status bar. Unfortunately, I also had the list of users in a dropdown elsewhere on the form. When I tried to change the dropdown, therefore, it knew that the data was already in use. Once I did a separate linq query for my form status bar, everything worked. I know it's expected behavior, but it was pretty frustrating.

like image 27
Carolyn B. Avatar answered Sep 28 '22 06:09

Carolyn B.