Reputation:
Hey Everyone i am using this code to remove multiple records in table. but it's give me an error.
"The object cannot be deleted because it was not found in the ObjectStateManager"
I am new in EF please help me what's wrong in my code.
listOfEntities = list of record which i want to delete from table
U = it is a type entity
using (var db = new DMContext())
{
db.SaveChanges();
}
Upvotes: 0
Views: 105
Reputation: 172428
It means that the entity is not attached. You can try like this
using (var db = new DMContext())
{
db.YourTableEntity.Attach(EntityToRemove);
db.YourTableEntity.Remove(EntityToRemove);
db.SaveChanges();
}
You cannot remove the entities which are detached, so you need to first attach them and then you can remove it.
To remove multiple records
foreach (var entity in entities)
{
Set<T>().Attach(entity);
Set<T>().Remove(entity);
}
SaveChanges();
Upvotes: 1