buda
buda

Reputation: 2372

Exclude Entities from SaveChanges

Can someone tell me how to exclude some entity from context before saving changes.

For Example i have 2 entities Actions and Users and i want to save only users?

Upvotes: 0

Views: 2971

Answers (5)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364269

I you changed an Action and you don't want to modify it you can either detach it from context or set it as unchanged (that is like hack).

Detaching entity:

context.Detach(action);

Setting state to unchanged:

context.ObjectStateManager.ChangeObjectState(action, EntityState.Unchanged);

Be aware that if you also changed relation between Action and User you will also need to reaset state of the relation by calling ObjectStateManager.ChangeRelationshipState.

Anyway you are doing something wrong because this situation should not happen. You should always modify only entities you want to save. If for any reason you need to modify only part of them your approach with clonning entities and modify them in other context is correct. Context is unit of work. You should modify only entities which are part of the same business transaction.

Upvotes: 2

AbdouMoumen
AbdouMoumen

Reputation: 3854

You can change the state of the changed objects (of type Action in your case) to "Unchanged" using the ObjectStateManager like so:

context.ObjectStateManager.ChangeObjectState(actionObject, EntityState.Unchanged);

I hope this helps :)

ps: you can get the list of modified objects using this:

var modifiedActions = context.Actions.Where(a=>a.EntityState!=EntityState.Unchanged);

Upvotes: 0

buda
buda

Reputation: 2372

I solve this by creating copy of entities Action with all child's (deep copy), and when i changed them i worked on the copy.

Upvotes: 0

Andy
Andy

Reputation: 8562

Well the best option would be not to modify the entities unless you really mean to change them. However you can change their state. The book Programming Entity Framework has details on this.

Upvotes: 0

Femaref
Femaref

Reputation: 61437

That's not possible as the SaveChanges method works on context level, not entity level.

Upvotes: 0

Related Questions