Foreign Key relationships in Entity Framework
by Joseph on Jul 6th in .Net 3.5, C#, Entity Framework
I received the following error while trying to use Entity Framework to update an object.
The property ‘AccessLevelID’ is part of the object’s key information and cannot be modified.
The object is a User, who has an AccessLevel foreign key.
The problem was in my code, which looked like this:
user.FullName = FullName;
user.LoginName = LoginName;
user.Password = Password;
user.AccessLevels.AccessLevelID = SecurityLevel;
user.Active = Active;
I was, in effect, trying to change the primary key of the AccessLevel in the AccessLevels table. Not good!
However, when I changed it to the following:
user.FullName = FullName;
user.LoginName = LoginName;
user.Password = Password;
user.AccessLevels = context.AccessLevels.First(level => level.AccessLevelID == SecurityLevel);
user.Active = Active;
Everything worked out.
The trick was setting the AccessLevel by treating it as an object. Almost like an Enum, but not quite.