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

时间:2012-04-05 11:12:30

标签: entity-framework-4.3

我正在尝试在EntityFramework 4.3 Code First中更新具有FK关系的实体。 我尝试通过调用:Entry(item).State = EntityState.Unchanged

来附加到相关的entites

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

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

提前致谢, 拉杜

3 个答案:

答案 0 :(得分:56)

您可以找到答案here

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

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

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

答案 1 :(得分: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;
    }

例如:

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

答案 2 :(得分:0)

如果您是从EF核心延迟加载场景到达的,在该场景中,当Entity附加到DbContext时,通过DbSet <>。Include()子句在数据层中填充了导航属性,然后将该实体分离并传递到业务层,请考虑将以下内容添加到您的DbContext.OnConfiguring(DbContextOptionsBuilder optionsBuilder)方法中: super 该错误将被忽略,并将返回最初包含在(d)中的值。

相关问题