EntityFramework Code First - Check if Entity is attached

流过昼夜 提交于 2019-11-27 03:03:53

问题


I am trying to update an entity with a FK relationship in EntityFramework 4.3 Code First. I try to attach to the related entites by calling: Entry(item).State = EntityState.Unchanged

I get the following exception: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

I do not update these items nor have an id property for them on my main entity. Is it possible to know which entities are attached or not ?

Thanks in advance, Radu


回答1:


You can find the answer here.

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

Place that code into your context or you can turn it into an extension like so.

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);
}



回答2:


You can use this method:

    /// <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;
    }

For example:

     if (!_objectContext.IsAttached(entity.EntityKey))
        {
            _objectContext.Attach(entity);
        }


来源:https://stackoverflow.com/questions/10027493/entityframework-code-first-check-if-entity-is-attached

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!