[c#] The property 'Id' is part of the object's key information and cannot be modified

i'm using Entity Framework 4.0 and having a silly problem that i can't figure out.

I have two tables:

  1. Contact: Id (primary key), Value, ContactTypeId (foreign key to ContactType)
  2. ContactType: Id (Primary key), Type (Home, Cell, Work, etc.)

Entity Framework created the following two entities:

  1. Contact: Id, Value, ContactType (Navigation Property)
  2. ContactType: Id, Type, Contact (Navigation Property)

I'm using the following code to get the contact and update the contact type for that particular contact:

Contact contact = dbContext.Contacts.Single(c => c.Id == 12345);
contact.ContactType.Id = 3;

Throws the following exception:

The property 'Id' is part of the object's key information and cannot be modified.

It looks so simple! I don't get it!

This question is related to c# foreign-keys entity-framework-4

The answer is


The entity that was created by the framework doesn't have a contact.ContactTypeId property. It automatically removed it and created the ContactType association inside the Contact entity.

The way to get it to work, as you suggested, is to create a ContactType object by querying the database and assigning it to contact.ContactType. For example:

Contact contact = dbContext.Contacts.Single(c => c.Id == 12345);
ContactType contactType = dbContext.ContactType.Single(c => c.Id == 3);
contact.ContactType = contactType;

in my case, i just set the primary key to table that was missing, re done the mappind edmx and it did work when you have the primary key tou would have only this

<PropertyRef Name="id" />

however if the primary key is not set, you would have

<PropertyRef Name="id" />
<PropertyRef Name="col1" />
<PropertyRef Name="col2" />

note that Juergen Fink answer is a work around


I am using EF 4.0 and WPF and I had similar problem, and .... found the issue that solved it (at least for me) in a very simple way.

Because, like you, I thought it must be simple to update a field in a table (i.e. in your case: Contact) that is referenced to by a foreignkey from another table (i.e. in your case: ContactType).

However, the Error Message: ".... is part of the object's key information and cannot be modified." only appears when you try to update a Primary Key (which wasn't my intention at all).

Had a closer look at the XML code of my EntityModel and found it:

<EntityType Name="Contact">
    <Key>
        <PropertyRef Name="ID" />
        <PropertyRef Name="contactTypeID" />   <!-- This second line caused my problem -->
    </Key>
    <Property Name="ID" Type="int" Nullable="false" />
    ...
    ...
</EntityType>

For some reason (maybe I made some foolish mistake within my database), when Visual Studio autogenerated for me the DataModel from my database, it added in that very table (Contact), where I wanted to update the field (ContactTypeID) a second PropertyRef (second line).

I just deleted that second PropertyRef:

<PropertyRef Name="contactTypeID" />

in both, the store model and the conceptual model and .... issue was solved :-)

Hence, remains like:

<EntityType Name="Contact">
    <Key>
        <PropertyRef Name="ID" />
    </Key>
    <Property Name="ID" Type="int" Nullable="false" />
    ...
    ...
</EntityType>

Updates and Inserts are now running smoothly like a baby .... :-)

Hence, good idea to check the XML of the datamodel to verify that only your PK is listed as PropertyRef. Worked for me ... :-)


Just hoping this helps someone else, after struggling for hours with this because i knew i wasnt updating the PK and i definitely had a PK. I had the PK value databound to a menu bar to show the current PK value and this was causing the issue.


This problem happens because you are referencing the same object more than once. This is not a limitation of EF, but rather a safety feature to ensure you are not inserting the same object with two different IDs. So to achieve what you are trying to do, is simply create a new object and add the newly created object to the database.

** This issue often happens inside loops. If you are using a while or foreach loop, make sure to have the New Created Object INSIDE the loop body.

try this:

Contact contact = dbContext.Contacts.Single(c => c.contactTypeId == 1234);
contact.contactTypeId = 4;
dbContext.AddObject(contact);
dbContext.SaveChanges();

Another strange behavior in my case I have a table without any primary key.EF itself creates composite primary key using all columns i.e.:

 <Key>
        <PropertyRef Name="ID" />
        <PropertyRef Name="No" />
       <PropertyRef Name="Code" />
   </Key>

And whenever I do any update operation it throws this exception:

The property 'Code' is part of the object's key information and cannot be modified.

Solution: remove table from EF diagram and go to your DB add primary key on table that is creating problem and re-add table to EF diagram it's all now it will have single key i.e.

<Key>
        <PropertyRef Name="ID" />
</Key>

In my case, I want to duplicate the object, but change the id, so I use this

Common.DataContext.Detach(object);

Work like a charm


first Remove next add

for simple

public static IEnumerable UserIntakeFoodEdit(FoodIntaked data)
        {
            DBContext db = new DBContext();
            var q = db.User_Food_UserIntakeFood.AsQueryable();
            var item = q.Where(f => f.PersonID == data.PersonID)
                  .Where(f => f.DateOfIntake == data.DateOfIntake)
                  .Where(f => f.MealTimeID == data.MealTimeIDOld)
                  .Where(f => f.NDB_No == data.NDB_No).FirstOrDefault();

            item.Amount = (decimal)data.Amount;
            item.WeightSeq = data.WeightSeq.ToString();
            item.TotalAmount = (decimal)data.TotalAmount;


            db.User_Food_UserIntakeFood.Remove(item);
            db.SaveChanges();

            item.MealTimeID = data.MealTimeID;//is key

            db.User_Food_UserIntakeFood.Add(item);
            db.SaveChanges();

            return "Edit";
        }

I had this happening when I was editing related objects from two separate contexts at the same time. Example:

DataContext ctxA = new DataContext();
DataContext ctxB = new DataContext();

Author orwell = new Author {Name = "George Orwell" };
ctxA.Add(orwell);
ctxB.Add(new Book {Name = "1984", Author = orwell});

ctxA.SaveChanges();
ctxB.SaveChanges();

My case was a little bit more convoluted (as this is obviously quite stupid) but in essence this was causing the error in my case.


For me the issue was caused by the lack of a Primary Key to my table, after setting a PK for the table the problem was gone


Try

contact.ContactType = differentContactType;

or

contact.ContactTypeId = 3;

You are trying to set the Id of the ContactType (of the Contact) to 3.


In my case, I was creating an object declared and initialized together. I just initialized in the constructor or what you can initialize the object when required.


There are two types of associations. Independant association where the related key would only surface as navigation property. Second one is foreign key association where the related key can be changed using foreign key and navigation property. So you can do the following.

//option 1 generic option

var contacttype = new ContactType{Id = 3};
db.ContactTypes.Attach(contacttype);
customer.ContactType = contacttype;

option 2 foreign key option

contact.ContactTypeId = 3;

//generic option works with foreign key and independent association

contact.ContactReference.EntityKey = new EntityKey("container.contactset","contacttypeid",3);

You should add

 db.Entry(contact).State = EntityState.Detached;

After the .SaveChanges();


In my case the error was appearing as I removed the KEY attribute of the ID field.

// [Key]
public long Id { get; set; }

So just putting the attribute back in it's place, made everything working again!

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to foreign-keys

Migration: Cannot add foreign key constraint The ALTER TABLE statement conflicted with the FOREIGN KEY constraint Can a foreign key refer to a primary key in the same table? Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why? MySQL Error 1215: Cannot add foreign key constraint MySQL Cannot Add Foreign Key Constraint Delete rows with foreign key in PostgreSQL How to remove constraints from my MySQL table? MySQL - Cannot add or update a child row: a foreign key constraint fails How to remove foreign key constraint in sql server?

Examples related to entity-framework-4

Entity Framework Join 3 Tables Entity framework self referencing loop detected The object 'DF__*' is dependent on column '*' - Changing int to double LEFT JOIN in LINQ to entities? Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why? The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties How to include a child object's child object in Entity Framework 5 EF Migrations: Rollback last applied migration? The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3