Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 690
Naor Avatar asked Dec 03 '25 06:12

Naor


1 Answers

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.

like image 137
Ladislav Mrnka Avatar answered Dec 04 '25 21:12

Ladislav Mrnka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!