开发者

query the attached entities

开发者 https://www.devze.com 2023-03-07 09:50 出处:网络
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 reco

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 upd开发者_开发知识库ated?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消