Code First - DbContext上没有Detach()方法 [英] Code First - No Detach() method on DbContext

查看:102
本文介绍了Code First - DbContext上没有Detach()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么DbContext对象上没有Detach方法,就像ObjectContext一样。  我只能假设这个遗漏是有意的,但我很难搞清楚原因。  我需要能够分离并重新附加实体
(例如,用于放入ASP.NET项目中的缓存)。  但是,由于我无法分离实体,当我尝试附加与先前上下文关联的实体时,我得到"实体对象不能被多个实例引用
of IEntityChangeTracker "例外。

I'm wondering why there is no Detach method on the DbContext object like there is for ObjectContext.  I can only assume this omission was intentional, but I have a hard time figuring out why.  I need to be able to detach and re-attach entities (for putting in the cache in an ASP.NET project, for example).  However, since I can't detach an entity, when I try to attach an entity that was associated with a previous context, I get the "An entity object cannot be referenced by multiple instances of IEntityChangeTracker" exception.

这里有什么指导?  我错过了什么吗?

What's the guidance here?  Am I missing something?

推荐答案

嗨Brian,

Hi Brian,

分离的能力将在下一个版本中可用(我们不希望在根DbSet级别公开它,因为它是一个更高级的操作)。

The ability to detach will be available in the next release (we didn't want to expose it at the root DbSet level because it is a more advanced operation).

在CTP4中你可以添加一个Detach方法如下;

In CTP4 you can add a Detach method as follows;

public class MyContext : DbContext
{
  ...

  public void Detach(object entity)
  {
    this.ObjectContext.ObjectStateManager.ChangeObjectState(entity, EntityState.Detached);
  }
}

 

~Rowan


这篇关于Code First - DbContext上没有Detach()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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