找到实体是否附加到dbContext的最合理的方法是什么? [英] what is the most reasonable way to find out if entity is attached to dbContext or not?
问题描述
当我尝试附加实体到上下文我得到一个例外
具有相同密钥的对象已经有
存在于ObjectStateManager。
ObjectStateManager无法跟踪
具有相同键的多个对象
这是预期的行为。
但是我想知道ObjectStateManager如何知道?
我想在
之前自己做这个检查如果你使用DbContext API(你提到ef-代码优先),您可以简单地使用:
context.YourEntities.Local.Any(e => e.Id == ID);
或更复杂
context.ChangeTracker.Entries< YourEntity>()。Any(e => e.Entity.Id == id);
如果是ObjectContext API,您可以使用:
$ {code> context.ObjectStateManager.GetObjectStateEntries(〜EntityState.Detached)
.Where(e =>!e.IsRelationship)
.Select(e => e.Entity)
.OfType< YourEntity>()
.Any(x => x.Id == id);
when i try to attach entity to context i get an exception
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key
This is expected behaviour.
But i would like to know how ObjectStateManager knows that? I would like to do this check by myself before
If you are using DbContext API (you mentioned ef-code-first) you can simply use:
context.YourEntities.Local.Any(e => e.Id == id);
or more complex
context.ChangeTracker.Entries<YourEntity>().Any(e => e.Entity.Id == id);
In case of ObjectContext API you can use:
context.ObjectStateManager.GetObjectStateEntries(~EntityState.Detached)
.Where(e => !e.IsRelationship)
.Select(e => e.Entity)
.OfType<YourEntity>()
.Any(x => x.Id == id);
这篇关于找到实体是否附加到dbContext的最合理的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!