tags:

views:

43

answers:

1

In the following code, I don't believe I am changing the foreign key, but I could be wrong. When I run it, I get the exception:

ForeignKeyReferenceAlreadyHasValueException

Here is the code:

UsersModule um = dc.UsersModules.Where(x => x.UserId == IdParam).FirstOrDefault();
int oldModuleId = um.ModuleId;
string oldModule = um.Module.ModuleName;

The error is thrown on the line:

string oldModule = um.Module.ModuleName

I don't know why I am getting this error because I am just trying to store the value of ModuleName into string oldModule, not change um.Module.ModuleName

A: 

LINQ works based on relational entities. So, whenever you need to set/read a foreign key value, it must be done by setting/reading the foreign entity instelad. Which means that shortcuts such as “Module.ModuleName” does not work very well.

Serkan Hekimoglu
I think the above code should work. Thats one of the cool features in Linq to Sql. And he is not trying to change anything, just read values.
Martin Ingvar Kofoed Jensen
I just fixed my answer. Set or Read doesnt matter.
Serkan Hekimoglu
ok so that explains the error while getting, but ModuleName is not a foreign key. Can you explain what the foreign entity is?
Xaisoft
Still not sure why the reading should fail. I just tried testing it and it worked.
Martin Ingvar Kofoed Jensen
I know that if you make a reading like this: um.Module, you can no longer change the value of um.ModuleId. But here, its only reading.
Martin Ingvar Kofoed Jensen