EntityFramework.NET: "On the provider connection, an issue occurred when beginning a transaction. Details may be found in the inner exception."

.net entity-framework

Question

Using Entity Framework in .NET I want to loop through a list of items returned from the database and make updates.

var qry = (from c in DBEntities.Customer select c);
foreach (Object item in qry)
{
  item.FirstName = .... 
  ... etc, other code here
  DBEntities.SaveChanges();
}

According to : http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/8a337036-d288-48d4-80d4-89e5a51eddd9?ppud=4 S Hargroves suggests converting to a IList and that is the solution.

Haven't tried that, I'm sure it will work, but even it works, I want to know why I can't update the item during the loop? This is occuring on my local development environment with no other users hitting the database.

Thanks ...

1
9
4/6/2010 10:14:52 PM

Popular Answer

When you update the database using SaveChanges on a query, the query is invalidated. The result set may have been changed by the update you performed.

By using ToList, you are triggering the execution of the query and bringing all the results from the database into memory. Your in-memory list is now concrete and not concerned with being a query anymore.

Because Object Queries use IEnumerable, its not ok to do something that modifies the list in a foreach.

I also believe this code would fail for the same basic reasons:

List<int> numbers = new List<int>() { 1,2,3,4,5,6};
foreach(var num in numbers)
  numbers.Remove(num); //Invalidates the Enumerator being used in the foreach
12
2/17/2011 8:30:39 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow