![](/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.