I have something like this:
public void Delete(T entity)
{
Context.DeleteObject(entity);
Context.SaveChanges();
}
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:
“An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.”
Whats wrong?
Example:
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
}
}
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
TabMasterandTabMasterViewModel, so the properties may be wrong named.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.