Reputation: 1
The method that i used to delete an item from database is throwing back the error "The object cannot be deleted because it was not found in the ObjectStateManager."
I followed multiple suggestions online to try to attach it but it was throwing back another error "Attaching an entity of type 'databaseName' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate."
public bool deleteItem(Item s)
{
bool success = false;
using (DBEntities cxt = new DBEntities())
{
var saving = (from i in cxt.Items
where i.Id == s.Id
select i).FirstOrDefault();
cxt.Entry(s).State = System.Data.Entity.EntityState.Deleted;
//cxt.Items.Attach(s);
cxt.Items.Remove(s);
int delete = cxt.SaveChanges();
if (delete == 1)
{
success = true;
}
return success;
}
}
Upvotes: 0
Views: 79
Reputation: 62318
You can do this with one database call instead of 2. Attach the entity and then call Remove on the DbSet to delete it.
public bool deleteItem(Item s)
{
bool success = false;
using (DBEntities cxt = new DecagonDBEntities())
{
cxt.Items.Attach(s);
cxt.Items.Remove(s);
int delete = cxt.SaveChanges();
bool success = delete == 1;
return success;
}
}
If you still want to retrieve it for validation
public bool deleteItem(Item s)
{
bool success = false;
using (DBEntities cxt = new DecagonDBEntities())
{
var itemToDelete = cxt.Items.SingleOrDefault(_ => _.Id == s.Id);
// validate itemToDelete like check for null etc
cxt.Items.Remove(itemToDelete);
int delete = cxt.SaveChanges();
bool success = delete == 1;
return success;
}
}
Upvotes: 1