该对象无法被删除,因为它在ObjectStateManager中找不到 [英] The object cannot be deleted because it was not found in the ObjectStateManager
问题描述
我有这样的东西:
public void Delete(T entity)
{
Context.DeleteObject(entity);
Context.SaveChanges();
}
我最终有一个异常:
该对象无法被删除,因为它在ObjectStateManager中找不到。
如果我尝试通过AttachTo()将实体添加到 objectContext中,我得到:
I end up wit a exception: "The object cannot be deleted because it was not found in the ObjectStateManager." If I try to add the entity to objectContext with AttachTo() I get:
具有相同密钥的对象已经存在于ObjectStateManager中,ObjectStateManager无法跟踪具有相同键的多个对象。
"An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."
有什么问题?
示例:
namespace CAFM.Data.Repository
{
public abstract class RepositoryBase<T> : IRepository<T>
where T : EntityObject
{
public RepositoryBase()
: this(new CAFMRepositoryContext())
{
}
static RepositoryBase()
{
}
public RepositoryBase(IRepositoryContext repositoryContext)
{
_context = repositoryContext ?? new CAFMRepositoryContext();
_entity = _repositoryContext.ObjectContext.CreateObjectSet<T>();
}
private readonly ObjectContext _context;
private readonly ObjectSet<T> _entity;
protected ObjectContext Context
{
get { return _context; }
}
protected IObjectSet<T> Entity
{
get { return _entity; }
}
#region IRepository Members
private string GetEntityName()
{
return string.Format("{0}.{1}", _entity.EntitySet.EntityContainer, _entity.EntitySet.Name);
}
public T Add(T entity)
{
var fqen = GetEntityName();
Context.AddObject(fqen, entity);
Context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
return entity;
}
public T Update(T entity)
{
Context.ApplyCurrentValues(GetEntityName(), entity);
Context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
return entity;
}
public void Delete(T entity)
{
Context.DeleteObject(entity);
Context.SaveChanges();
}
#endregion
}
}
推荐答案
您必须首先从您的上下文中获取要删除的实体。最好用主键进行比较。它可能看起来像这样,但我不知道 TabMaster
和 TabMasterViewModel
的对象结构,所以属性可能是错误的命名。
You have to fetch the entity you wish to delete from your context first. Best to do this with a comparison of the primary key. It could look like this, but i do not know the object structure of TabMaster
and TabMasterViewModel
, so the properties may be wrong named.
public void Delete(TabMasterViewModel entity) {
TabMaster des = _tabmasterRepository.FirstOrDefault( e.Id = entity.ID );
if (des != null) {
_tabmasterRepository.Delete(des);
}
}
您已经创建了一个新的实体,并映射了您对该实体的视图模型。但是上下文不知道实体,所以他不能删除它。
You have created a new Entity and mapped the values from your view model to that entity. But the context does not know of the entity, so he could not delete it.
这篇关于该对象无法被删除,因为它在ObjectStateManager中找不到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!