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?

Answers


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.


Need Your Help

How to create custom fixed-width buttons in Foundation 5 using button-group-style mixin

css zurb-foundation

I'm trying to create a custom button bar centered within a row using Foundation 5 mixins, where the buttons are of the same width based off the size of the largest button in the group. In the vanilla

Styling site to customer specific based on subdomain

javascript css subdomain appendto

I am trying to style a site based on the subdomain header used to access the site so for instance it will be: