Update part of primary key Entity Framework 4.0

后端 未结 2 1799
不思量自难忘°
不思量自难忘° 2021-01-18 05:45

I\'ve a table with a compose primary key (3 columns):

UTP_ID (ITEMId)
UTS_ID (CategoryID)
USS_ID (SubCategoryID)

When I try to change SubCa

相关标签:
2条回答
  • 2021-01-18 06:15

    EF implements an Identity Map between primary key property values and object references. It doesn't allow to change the key for the same object instance.

    I would do this with direct SQL:

    objectContext.ExecuteStoreCommand(
        "UPDATE MyTable SET USS_ID = {0} WHERE UTP_ID = {1} AND UTS_ID = {2} AND USS_ID = {3}",
        Convert.ToInt32(ddlSubSetor.SelectedItem.Value),
        utl.UTP_ID, utl.UTS_ID, utl.USS_ID);
    

    Make sure that your entity utl is detached from the context because this code directly writes into the database table and the entity doesn't get any information about this change. But this avoids having to delete and recreate the entity (which might be impossible due to existing foreign key constraints on the old row in the database).

    0 讨论(0)
  • 2021-01-18 06:35

    As a result of being part of the entity key the object needs to be deleted from the context and re-attached with the new primary key value.

    The Entity Framework works by having a context which manages the state of the entities, a collection of entities (basically the table) and the entity itself (a row of data). As data is read from the database it is added to the entity's collection which in turn is managed by the context for changes of state. Changing an Entity's key is really deleting the entry from the database and inserting a new one. As a result to change an entity key, first delete the entity from it's collection, detach the entity object to allow key modification, change the primary key value and re-attach the entity to the collection. Finally call save changes in the context to apply the changes to the database.

    The following code should produce the desired results:

    Context.UTLs.DeleteObject(utl);
    Context.UTLs.Detach(utl);
    Context.SaveChanges();
    utl.USS_ID = Convert.ToInt32(ddlSubSetor.SelectedItem.Value);
    Context.UTLs.AddObject(utl).
    Context.SaveChanges();
    
    0 讨论(0)
提交回复
热议问题