C# – Entity Framework: Changing the values of a table

asp.netcentity-framework

I have a table called say Table1 which has a column that is a primary key in another table.

I want to change this value so I try
Table1.OtherTableWithID.ID = Myvalue
But i get the error
"The property 'ID' is part of the object's key information and cannot be modified. "

So how can i modify this value seeing that I cannot access it through Table1.ID?

Best Answer

I think you're describing a foreign key :-) Quoting from my answer in another question, you can either select the associated object and assign it that way:

table1Item.Table2 = ctx.Table2.First(t => t.ID == newID);

Or, if you don't want to query the database to get the foreign key entity, or you haven't got the entities set up that way for whatever reason you can also use an EntityKey to the same effect:

tableItem.Table2Reference.EntityKey = new EntityKey("MyDb.Table2", "ID", newID);