什么是找出如果实体连接到的DbContext或不是最合理的方式是什么? [英] what is the most reasonable way to find out if entity is attached to dbContext or not?

查看:109
本文介绍了什么是找出如果实体连接到的DbContext或不是最合理的方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试实体附加方面,我得到一个异常

when i try to attach entity to context i get an exception

与已经相同键的对象
  存在于ObjectStateManager。该
  ObjectStateManager无法跟踪
  具有相同键的多个对象

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key

这是预期的行为。

但我想知道怎么ObjectStateManager知道?
我想自己做这个检查之前

But i would like to know how ObjectStateManager knows that? I would like to do this check by myself before

推荐答案

如果你正在使用的DbContext API(你提到的EF-code-第一),你可以简单地使用:

If you are using DbContext API (you mentioned ef-code-first) you can simply use:

context.YourEntities.Local.Any(e => e.Id == id);

或更复杂的

context.ChangeTracker.Entries<YourEntity>().Any(e => e.Entity.Id == id);

在ObjectContext的API的情况下,你可以使用:

In case of ObjectContext API you can use:

context.ObjectStateManager.GetObjectStateEntires(~EntityState.Detached)
                          .Where(e => !e.IsRelationship)
                          .Select(e => e.Entity)
                          .OfType<YourEntity>()
                          .Any(x => x.Id == id);

这篇关于什么是找出如果实体连接到的DbContext或不是最合理的方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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