views:

245

answers:

2

I have a LinqToSql query that returns an array of Article objects like so:

return db.Articles.ToArray();

I then loop over this array and start to delete some items that meet a certain criteria, for simplicity let's say I delete them all, like so:

foreach (var item in array) 
    db.articles.DeleteOnSubmit(item);

The call to DeleteOnSubmit(entity) throws an invalid operation exception, it's message says "Can not delete an entity that has not been attached". I modified the code to get the entity first then delete it and it worked just fine. Here's the working code:

db.DeleteOnSubmit(db.Articles.Where(c=>c.Id == item.Id))

Now, I know it would work if I modified the repository to return IQueryable instead of a native array, I just don't understand why? Does ToArray has anything to do with this invalid operation exception?
Thanks.
ps: db is a reference to a DataContext object.

+1  A: 

I suspect your using different DataContexts when selecting entities and when submitting changes. If this is the case, the error is natural and would still happen if you returned an IQueryable instead of a native array. Either you Attach an entity to the new data context or you use the same where you selected the initial entities.

bruno conde
No, I'm using one DataContext only!
Galilyou
In that case I can't reproduce your problem ... I did a quick test and I can deleteOnSubmit entities either through IQueryable or ToArray
bruno conde
Really? I mean, Oh! I will update and add the exact scenario with all the code.
Galilyou
+1  A: 

Can you put it all in one method and try?

The answer is "No", it doesn't.

Unless you are using differen't db for delete than select (could happenw ithout you realize it) or db.ObjectTrackingEnabled is set to false somewhere.

Mohamed Meligy
Meligy :) you're here! No, I'm using one datacontext, and I didn't touch ObjectTrackingEnabled anywhere in my code-I assume it's set to true by default. Anyways, I'm gonna double-check and report back to you guys here in SO.
Galilyou
Just try to put all ur code in one method and see. If the problem still exists, try to send the full method code or (if possible) a simple reproduce VS proj.
Mohamed Meligy
Any updates whether this answer is valid for your question?
Mohamed Meligy