0

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?

Alexandre Rondeau
  • 2,667
  • 24
  • 31
Juan Pablo Gomez
  • 5,203
  • 11
  • 55
  • 101
  • 5
    why is it in the database before it is confirmed? – default Oct 15 '13 at 19:52
  • Because we need to track availability of inventory at any time. All documents are tracked as part of purchase intention until they are confimed or rejected.. – Juan Pablo Gomez Oct 15 '13 at 20:11
  • 1
    You cannot update The PK using EntityFramework. If you really want to get around it. You could write a store procedure and call it. But maybe you could change your data model to use a Identity PK and use your string as an unique index – Alexandre Rondeau Oct 15 '13 at 20:17
  • This question explains why it's not possible to do this using EF [Update primary key value using entity framework](http://stackoverflow.com/questions/1367751/update-primary-key-value-using-entity-framework/6012040) – Alexandre Rondeau Oct 15 '13 at 20:19
  • @allo_man Tks alot for your help, stored procedure sounds fine. – Juan Pablo Gomez Oct 15 '13 at 20:33
  • Having to modify PKs never sounds fine. It reveals bad design. A PK should never have a meaning to the business domain. Use a "confirmed" flag or an alternate key as suggested above. – Gert Arnold Oct 16 '13 at 19:55

1 Answers1

3

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).

Chaya Sulman
  • 111
  • 4