1

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.

4

2 回答 2

1

你能把它全部放在一种方法中试试吗?

答案是“不”,事实并非如此。

除非您使用不同的 db 进行删除而不是选择(可能在您没有意识到的情况下发生)或 db.ObjectTrackingEnabled 在某处设置为 false。

于 2009-10-26T12:05:14.787 回答
1

我怀疑您在选择实体和提交更改时使用不同的 DataContexts。IQueryable如果是这种情况,错误是自然的,如果您返回 an而不是 native ,仍然会发生错误array。您Attach可以是新数据上下文的实体,也可以在选择初始实体的位置使用相同的实体。

于 2009-10-26T10:40:10.300 回答