Nate Pet
Nate Pet

Reputation: 46222

LINQ Entity Framework - The object cannot be deleted because it was not found in the ObjectStateManager

I am using Entity Framework. I am trying to get the results from linq and then do a delete on them as such:

    IEnumerable<tblAVAL> tblval = db.tblVALs.Where(p => p.PgrID == prid);
    db.DeleteObject(tblval);
    db.SaveChanges(); 

Note that tblval returns a collection. I get the following message though:

The object cannot be deleted because it was not found in the ObjectStateManager.

If I do the following it works:

    tblAVAL tblval = db.tblVALs.First(p => p.PgrID == prid);
    db.DeleteObject(tblval);
    db.SaveChanges(); 

How can I get it to to delete with a collection that has more than 1 rows returned?

Upvotes: 2

Views: 2786

Answers (1)

Ivo
Ivo

Reputation: 8352

When you pass the collection to the DeleteObject method, it tries to map the Collection object as it is an entity. What you need to do is to iterate the collection and delete the items.

foreach( var tblav in db.tblVALs.Where(p => p.PgrID == prid))
    db.DeleteObject(tblav);

db.SaveChanges(); 

EntityFramwork doesn't support bulk deletes, updates and inserts. http://magiq.codeplex.com has an implementation for Linq-to-Sql and EntityFramework but without all the features. Maybe what is done fits your needs.

Upvotes: 1

Related Questions