Search code examples
c#entity-frameworkentity-framework-4data-access-layer

Is it possible to SaveChanges except an entity?


The Problem

Initiating a new entity(call it "TargetEntity") to insert, I'm using another entity properties(call it "TemplateEntity").

some properties of TargetEntity are getting the values of TemplateEntity properties and its' navigation properties.

in some special cases, I have to make some changes on TemplateEntity props and navigation props values. For example assume this is the TargetEntity to be fill:

TargetEntity
- prop1
- prop2
- prop3

and this is the TemplateEntity with value:

TemplateEntity
- prop1
- NavProp1.prop2
- NavProp2.prop3

I want to apply some changes on TemplateEntity like this:

TemplateEntity to be applied
- prop1 * index1
- NavProp1.prop2 * 0
- NavProp2.prop3 *index2

Restrictions and Conditions

  1. I'm working with entities, no POCO, no DTO. there are many nested navigation properties and it's very complex to make a flat object of it, or clone an offline nested object.

  2. The TemplateEntity is getting used in many method. Each method have their own Context and save changes (i.e logs and such things).

The Question

How can I save changes, and avoid an entity like TemplateEntity and its' navigations change in DB?


Solution

  • It is not possible to exclude / skip entity update from unit of work unless you:

    • Reconfigure states in the graph for that entity - it means you must traverse the entity graph and set everything to unchanged
    • Not include the entity in unit of work in the first place - the entity graph must not be attached to the context - this usually leads to cloning of object graph which is only possible through serialization and deserialization (your entities already support this through DataContractSerializer).