Update part of primary key Entity Framework 4.0

后端 未结 2 1800
不思量自难忘°
不思量自难忘° 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: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();
    

提交回复
热议问题