views:

563

answers:

2

hey guys, ok, here's 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?

cheers!

A: 

Hi Andy,

Shot in the dark here: Any chance the ImageID field on the image entity is nullable?

Doesn't answer either question I know...

Daniel M
+1  A: 

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.

DamienG
that's exactly the problem. In a test scenario I ran it once without debugging, and in a second case i ran it by watching various properties. This caused the error. Obviously the error can occur without debugging, if at any time in your code you check the value of said property.
andy
which is weird behavior because really, I'm only checking the value...and if it is in fact "null" or "Nothing", then nothing should load...no?
andy
If you take a look at the code you'll see that the property accessor is a lazy-load implementation. When you access the property it heads to the database with the foreign key so it can create the object and assign it to the property. Once it has done this it doesn't like you changing the foreign key because then there is an inconsistency as the FK and entity property no longer match.
DamienG
hmm...bug? or just a badly designed implementation? because really, there's no intuitive logic to this design...?
andy