Naor
Naor

Reputation: 24063

query the attached entities

I am doing several insert commands before doing SaveChanges.

Is there a way to query the attached entities (that I inserted right now before the SaveChanges) in order to check whether a specific record was added or updated?

Upvotes: 3

Views: 69

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

Yes there is a way. ObjectContext instance offers property called ObjectStateManger. ObjectStateManager manages all attached entities and it knows their state:

ObjectStateEntry entry = context.ObjectStateManager.GetObjectStateEntry(attachedEntity);
EntityState state = entry.State;

If you need to get all modified or added entities you can use:

var entities = context.ObjectStateManager
                      .GetObjectStateEntries(EntityState.Added | EntitiSate.Modified)
                      .Select(e => e.Entity);

You can further use OfType to select only entities of some type. You can also use this logic SaveChanges as described many times on Stack Overflow - for example here.

Upvotes: 2

Related Questions