扩展方法中的实体框架4.1上下文

时间:2013-06-26 10:53:25

标签: c# entity-framework-4.1 extension-methods

当我运行此代码时,它说:

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.

我可以想象这里的情况。可能是因为:

//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

这是扩展方法的主要部分

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();
    }
}

扩展方法有效,实体从db中删除。但是当程序来到

cont.SaveChanges();

行,它会抛出错误。我假设,这个错误出现是因为我使用另一个MyEntity()类改变了另一个方法中的实体。所以我一直在寻找一种刷新另一种方法的方法。但我不能......

2 个答案:

答案 0 :(得分:4)

我认为你应该将上下文作为参数传递给delete方法。 不要在方法中构造新的上下文,并从中删除 - 而是从原始上下文中删除。

答案 1 :(得分:0)

我通过使用omer schleifer的建议以及我在另一个主题上找到的东西来解决这个问题。

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

我在delete方法中使用了上下文作为参数,但是它抛出了一个错误

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

然后我改变了我使用的for循环,就像这个

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

而不是

foreach (Product m in p)
{
}

问题已经解决。

感谢您的回答......