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?
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.
That's not possible as the SaveChanges
method works on context level, not entity level.
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.
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.
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);
精彩评论