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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With