C# .NET - Get the following exception when update with entity framwork

Asked By mostafa hamdy on 01-Jun-11 11:35 AM
Hello all
I have some  method which tried to update some record in the Db , I'm using the entity framwork , but I get the following  exception :Trans_key is part of the object's key information and cannot be modified

my code  which updates the record is as the following:

TRANS_Keys dalObject = null;

dalObject.TranslationKeyStart = businessObject.TranslationKeyStart;

dalObject.TranslationKey = businessObject.TranslationKey;

return dalObject;

please if any body get what I mean and can help me please send me or tell me about some url may help me in solving this issue
Regards
Mostafa

Kirtan Patel replied to mostafa hamdy on 01-Jun-11 11:47 AM
look at below article this will help you in this case :)

http://blogs.msdn.com/b/vsdata/archive/2009/10/16/entity-data-model-working-with-foreign-key-when-you-don-t-have-it.aspx

Anoop S replied to mostafa hamdy on 01-Jun-11 12:38 PM

You cannot update a primary key, but that is not a limitation of entity framework, but a very fundamental rule of database development. A primary key is assigned once to a row in a table and makes this row unique.
Maybe you can update the key in some ways, but this violates definitely the definition of a primary key.

So, just don't do it, there are other ways to accomplish what you are trying to do.

Jitendra Faye replied to mostafa hamdy on 02-Jun-11 12:40 AM
By using this code your are inserting data into TRANS_Keys Object (Entity).
but in you code you didn't create memory for that, you have declared object but it is null.

first create object with new operator.


change your code like this-

TRANS_Keys dalObject = new TRANS_Keys();

dalObject.TranslationKeyStart = businessObject.TranslationKeyStart;

dalObject.TranslationKey = businessObject.TranslationKey;

return dalObject;

AND LET ME KNOW.

mostafa hamdy replied to Kirtan Patel on 02-Jun-11 06:52 AM
Hi Kirtan
really many thanx about ur help , I read the article in the URL u have sent me , and I do applied it to my code but after I do my code I get the following excption:

"The object cannot be attached because the value of a property that is a part of the EntityKey does not match the corresponding value in the EntityKey."
and my code after update is as the following:

var ekeyvalue = new KeyValuePair<string, object>[]

{

new KeyValuePair<string,object>("TranslationKey",businessObject.TranslationKey),

new KeyValuePair<string,object>("TranslationKeyStart",businessObject.TranslationKeyStart)

};

EntityKey ek = new EntityKey("Entities.TRANS_Keys", ekeyvalue);

TRANS_Keys to = new TRANS_Keys();

to.EntityKey = ek;

context.AttachTo("TRANS_Keys", to);

context.SaveChanges();
please if u get the problem and can help me again  or tell me about some URL may help me in solving it I will be great thankfull for u
Regards
Mostafa
regards