GibboK
GibboK

Reputation: 73918

Entity Framework 4 - How to Update an Object

net 4 and c#.

I have an Object (myContentObj) and a navigational property (CmsGroupsTypes).

I need update the navigational property for specific objct.

At the moment I use this code below to remove the current association and add a new one, so I can Update the navigational property.

Albeit my code works, I would like to know if you know a better approach to it... I am not sure if exist an UPDATE method or similar in EF4.

Thanks for your help!

            // Remove object
            myContentObj.CmsGroupsTypes.Remove(myCurrentGroupTypeObj);
            // Update object
            myContentObj.CmsGroupsTypes.Add(myNewGroupTypeObj);
            context.SaveChanges();

Upvotes: 0

Views: 3863

Answers (3)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

This is the correct approach. You are modifying a navigation property = you are modifying a relation between entities. To remove the relation between entities you must remove the related entity from the navigation property. To add the relation between entities you must add the related entity to the navigation property.

The only issue can be if you call Add with an entity which exists in DB but it is not loaded from the database (a dummy object or a detached entity). In this case EF will try to insert your entity to the database again. To avoid that you must either use an attached entity (load it from DB) or set its state to Unchanged.

Other way is using foreign association where a dependent entity also offers a foreign key property. You can change relation simply by setting this property to id of the parent. This is usable only for one-to-one and one-to-many relations.

Be aware that removing the entity from the parent's navigation property doesn't delete entity the child entity from database. So if the relation to parent is dependent you must also delete it or SaveChanges throws exception.

Upvotes: 1

Wojtek Turowicz
Wojtek Turowicz

Reputation: 4131

Context keeps track of your objects, just get it from context, change its data and Context.SaveChanges()

Upvotes: 1

Jonathan
Jonathan

Reputation: 12025

I'm not really sure about this, and I can't check it right now, but I think you can directly change the myCurrentGroupTypeObj properties, and then do

ObjectStateManager.ChangeObjectState(myCurrentGroupTypeObj , EntityState.Modified);

I hope it works. If not, please let me know.

Upvotes: 0

Related Questions