找到实体是否附加到dbContext的最合理的方法是什么? [英] what is the most reasonable way to find out if entity is attached to dbContext or not?

查看:128
本文介绍了找到实体是否附加到dbContext的最合理的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试附加实体到上下文我得到一个例外


具有相同密钥的对象已经有
存在于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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆