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)
您可以使用此方法:
/// <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)
| 归档时间: |
|
| 查看次数: |
23583 次 |
| 最近记录: |