EntityFramework Code First - 检查是否附加了实体

Rad*_*ila 29 entity-framework-4.3

我试图在EntityFramework 4.3 Code First中更新具有FK关系的实体.我尝试通过调用:Entry(item).State = EntityState.Unchanged来附加到相关的entites

我得到以下异常:ObjectStateManager中已存在具有相同键的对象.ObjectStateManager无法使用相同的键跟踪多个对象.

我不更新这些项目,也不在我的主实体上为它们设置id属性.是否可以知道附加了哪些实体?

提前谢谢,Radu

Tri*_*ran 67

你可以在这里找到答案.

public bool Exists<T>(T entity) where T : class
{
    return this.Set<T>().Local.Any(e => e == entity);
}
Run Code Online (Sandbox Code Playgroud)

将该代码放入您的上下文中,或者您可以将其转换为类似的扩展名.

public static bool Exists<TContext, TEntity>(this TContext context, TEntity entity)
    where TContext : DbContext
    where TEntity : class
{
    return context.Set<TEntity>().Local.Any(e => e == entity);
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.这也对我有所帮助.另外注意上面的功能.你需要把T:class放在哪里,否则编译器就会抱怨. (2认同)
  • TContext 似乎没有必要。让第一个参数的类型为 DbContext - public static bool Exists&lt;TEntity&gt;(this DbContext context, TEntityEntity)... (2认同)

Vic*_*orV 7

您可以使用此方法:

    /// <summary>
    /// Determines whether the specified entity key is attached is attached.
    /// </summary>
    /// <param name="context">The context.</param>
    /// <param name="key">The key.</param>
    /// <returns>
    ///   <c>true</c> if the specified context is attached; otherwise, <c>false</c>.
    /// </returns>
    internal static bool IsAttached(this ObjectContext context, EntityKey key)
    {
        if (key == null)
        {
            throw new ArgumentNullException("key");
        }

        ObjectStateEntry entry;
        if (context.ObjectStateManager.TryGetObjectStateEntry(key, out entry))
        {
            return (entry.State != EntityState.Detached);
        }
        return false;
    }
Run Code Online (Sandbox Code Playgroud)

例如:

     if (!_objectContext.IsAttached(entity.EntityKey))
        {
            _objectContext.Attach(entity);
        }
Run Code Online (Sandbox Code Playgroud)

  • 我做了一些性能测试,并且(令人惊讶地)发现ObjectStateManager.TryGetObjectStateEntry比Set <TEntity>()慢70多倍.Local.Any( (9认同)