Foreign Key relationships in Entity Framework

by Joe 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.

3 Comments

  1. Anonymous

    23rd July 2009

    Thanks a lot this helped me out after searching for a while, did exactly the same thing and just couldn't get it..

  2. Durai karthik

    23rd July 2009

    Hi , i am getting the same error . where could i set Security level for my problem . Whether in EDMX .cs or in my class file?

    I am not getting security level method also.

    Kindly advice.

  3. Joe

    23rd July 2009

    Durai, I'm not quite sure what you are asking. Can you post a sample?

Leave a Reply

Powered By Wordpress Designed By Ridgey