Juan Pablo Gomez
Juan Pablo Gomez

Reputation: 5544

EF Change Primary key value

I have an EF entity with string PK, an other entityes related to it

public class E1
{
    public string PK {get;set;}
    .....   
} 

During my proccess I assign a temporary PK to all my structure (E1 and related entities) awaiting the user to confirm the document.

If user confirm, I assign a definitelly PK and the database updates all ONCASCADE

My problem is when I'm trying to change the state of E1, it throws this exception

Property 'PK' is part of the info of object key, couldn't be modified

How can I do to avoid this Exception?

Upvotes: 0

Views: 2246

Answers (1)

Chaya Sulman
Chaya Sulman

Reputation: 121

This is an old question, but I figured I'd throw an answer up there as I just ran into a similar issue where I had to update a primary key value on an entity. I executed a SQL command directly on the database to update the primary key value, and then I disposed and re-instantiated the context. It worked great. Here is a code example:

if(theEntity.PKValue != newPkValue)
{
    context.Database.ExecuteSqlCommand("UPDATE table SET PKValue = @p0 WHERE identifier = @p1", newPKValue, identifierValue);
    context.Dispose();
    context = new ContextName();
    theEntity = context.tables.Single(e => e.identifier == identifierValue);
}

(Since you are updating the primary key using straight SQL, you shouldn't have any issues using the old primary key value as the identifier if you have to. However if the primary key value is the identifier, remember to search for the new primary key value when you reset the entity).

Upvotes: 3

Related Questions