Question

When I run this code it says that:

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

I can imagine the situation here. Probably because of this:

//Default.aspx.cs
MyEntity cont = new MyEntity();
IEnumerable<Product> p = from c in cont.Products.AsEnumerable()
                select c;
Product example = p.ToArray()[0];
example.Delete(); // This Delete method is an extension method which you'll see in below.
//I also have some other stuff like

IEnumerable<Category> cc = from n in cont.Categories.AsEnumerable()
                                 select n;
cont.Categories.Remove(cc.ToArray()[0]);
cont.SaveChanges(); //throws the error

Here is the main part of the extension method

public static bool Delete(this Product pro,bool SetNull = false) {
    using (var en = new MyEntity()) {
        IEnumerable<Product> s = from ss in en.Products
                                where ss.ID == pro.ID
                                select ss;

        en.Products.Remove(s.SingleOrDefault());
        en.SaveChanges();
    }
}

The extension methods works, the entity removes from db. But when the program comes to the

cont.SaveChanges();

line , it throws the error. I assume, this error comes up because i've changed the entities within some another method using another MyEntity() class. So i've searched to find a way to refresh the other one. But i couldn't ...

Was it helpful?

Solution

I think you should pass the context as a parameter to the delete method. Do not construct a new context in the method, and delete from it - delete from the original context instead.

OTHER TIPS

I figured it out by usign omer schleifer's advice and also something i found on another topic.

New transaction is not allowed because there are other threads running in the session LINQ To Entity

I used the context as a parameter in delete method but it thrown an error

New transaction is not allowed because there are other threads running in the session

And then i changed the for loop that i use, like this

foreach (Product m in p.ToList())
{
}

instead of this

foreach (Product m in p)
{
}

and problem has resolved.

Thank you for your answers...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top