tag:blogger.com,1999:blog-820160698298723786.post928130885346396626..comments2024-01-05T21:22:41.693+11:00Comments on Dan's Developing Days: LINQ to Entities and the “Collection was modified” exception – A solution!Oddhttp://www.blogger.com/profile/08305441026478320214noreply@blogger.comBlogger3125tag:blogger.com,1999:blog-820160698298723786.post-79235882927185782712012-02-02T00:06:30.033+11:002012-02-02T00:06:30.033+11:00Or I found this neat way of doing it (not sure how...Or I found this neat way of doing it (not sure how efficient though):<br /><br />foreach (Item item in _Entities.Item.ToList())<br /><br />{<br /><br /> if (/* criteria */)<br /><br /> {<br /><br /> _Entities.Item.Remove(item);<br /><br /> }<br /><br />}Davidhttp://robotification.comnoreply@blogger.comtag:blogger.com,1999:blog-820160698298723786.post-12406086377763133382010-08-27T08:51:05.678+10:002010-08-27T08:51:05.678+10:00Linq-based Suggestion:
entity.Colletion.ForEach(s...Linq-based Suggestion:<br /><br />entity.Colletion.ForEach(s => /* modifications */)<br />entity.Save();<br /><br />IEnumerable ForEach impl:<br /><br />public static void ForEach(this IEnumerable enumerable, Action action)<br />{<br /> foreach (var item in enumerable)<br /> action.Invoke(item);<br />}Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-820160698298723786.post-26700437265260059542010-02-13T01:55:53.611+11:002010-02-13T01:55:53.611+11:00Here's how I did it by chaining a couple of en...Here's how I did it by chaining a couple of entity framework queries to extract those not required, which I then removed. The new list is required to prevent the exception you detailed above.<br /><br />private void RemoveSalesProduct(Entities db, Store store, ICollection products)<br />{<br /> var unrequired = new List(store.Product.Where(x => products.All(y => y != x.ProductID)));<br /> foreach (var product in unrequired)<br /> {<br /> store.Product.Remove(db.Product.First(p => p.ProductID == product.ProductID));<br /> }<br />}Marcusnoreply@blogger.com