![](/img/trans.png)
[英]Why do I get the “name does not exist in current context” error even though I'm using name in the same scope as its declaration
[英]Why is my code triggering multiple DB context though I'm only using 1 context
对不起,如果代码有点长。 我只有一种情况。 但我收到以下错误
IEntityChangeTracker的多个实例不能引用一个实体对象。
以下是触发它的行
第163行:foreach(SessionVariables.ligneNouvelleFacture中的ligne)
第164行:{
第165行:dc.ligne.Add(l);
第166行:}
因此,我要做的只是使用EntityFramework上下文类默认方法在DB中插入数据。 数据存储在对象的静态列表中,我使用foreach
进行迭代,然后在保存更改dc.SaveChanges()
之前将其添加到上下文中。
我不知道为什么会收到该错误,因为我仅在此Webform中的代码背后创建了上下文的单个实例。 并且该上下文变量用于在页面加载时填充gridview。
你能帮我弄清楚吗? 下面是我的代码
public class Utilities()
{
public static list<object> myList = new list<object>();
}
public partial classe MyWebform : Page
{
MyContext cnx = new MyContext();
potected void Page_Load()
{ // Do something with the context "cnx" and static list of utilities class}
protected void button_Click(...)
{
//Also do something with the context "cnx" and the static list of utilities class
}
}
UPDATE
在下面的提示之后,以及在MSDN上看到Dispose
并阅读了Entity Framework和context dispose之后 ,我尝试了一种似乎可行的新方法。 希望它还不错。 我可能会错误地实现using
但似乎并未隐式dispose
。
public class MyWebForm .....
{
// I do no declare a context variable object so that every time a context must be used, I do the following.
using (MyContext cnx = new MyContext())
{
// ...do something with cnx
cnx.Dispose(); // This line appears to be compulsory to avoid multiple context error
}
}
希望这可以帮助某人
您正在创建多个上下文。 每次加载页面时,都会创建一个新页面。 您保留一个静态的对象列表,然后尝试将它们一次又一次地添加到上下文中,即使它们已经在一个上下文中也是如此。 这将导致错误。
这也可能导致内存泄漏,因为每个对象都有一个单独的上下文,由于这些对象处于活动状态,因此无法释放该上下文。 您应该重新设计功能。 是否有必要将对象保留在内存中? 为什么需要再次将所有对象而不是新对象添加到上下文中?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.