I'm getting the following error when I try to delete an entity:
"An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."
I have read the other posts here related to this error and have tried detaching the filter with no luck. maybe I'm missing something simple or should use a different approach to delete these filters(I already tried remove method)? Any help would be greatly appreciated.
Here's the code: I'm using ASP.NET 4.5 and EF 5. The simple repository class this is in has a private dbContext being initialized in the repository constructor and destroyed in the destructor.
namespace AuditLog.Repositories
{
public class FilterSetRepository : IFilterSetRepository
{
private readonly AuditLogEntities _ctx;
/// <summary>
/// Default constructor
/// </summary>
public FilterSetRepository()
{
_ctx = new AuditLogEntities();
}
/// <summary>
/// Destructor
/// </summary>
~FilterSetRepository()
{
_ctx.Dispose();
}
The error gets thrown on the line that has _ctx.Entry(filter).State = EntityState.Deleted;
inside the foreach loop (below). The entity called FilterSet has a list of Filter entities that must be deleted from their table before I can delete a FilterSet. I can provide the class code showing them if necessary.
Just above the offending line is where I tried the detach method, but it said it couldn't detach because a key wasn't already attached.
/// <summary>
/// Delete a particular filter set and its filters.
/// </summary>
/// <param name="filterSet">The filter set to be deleted.</param>
public void DeleteFilterSet(FilterSet filterSet)
{
// First delete the child elements
var filterRepository = new FilterRepository();
foreach (var filter in filterRepository.GetFiltersBySets(filterSet))
{
_ctx.Entry(filter).State = EntityState.Deleted;
_ctx.SaveChanges();
}
// ...then delete the filter set
_ctx.Entry(filterSet).State = EntityState.Deleted;
_ctx.SaveChanges();
}
Thank you in advance for your help!