2012-08-09 91 views
2

我想解決這個問題,並沒有閱讀有關此錯誤的內容,但無法找出解決方案。 我正在構建一個簡單的產品類別場景使用實體框架的winforms應用程序。 這是我的模型的快照。 EdmxObjectContext實例已被處置 - Winforms實體框架

在ProductService類的代碼檢索所有的產品是

public static List<Product> GetAllProducts() 
{ 
    List<Product> products = new List<Product>(); 
    using (var entity = new SUIMSEntities1()) 
    { 
     products = (from p in entity.Products 
        select p).ToList(); 
     return products; 
    }    
} 

代碼的產品代碼背後,是

List<Product> prods=ProductServices.GetAllProducts(); 
dgvProducts.DataSource = prods; 

當我嘗試加載產品在DataGridView中,以下錯誤顯示如下: enter image description here

您能否請告訴我是什麼導致了這個問題?

編輯: 的包含的伎倆,在這種特定的情況下,我改變了GetAllProducts(),如下

 public static List<Product> GetAllProducts() 
     { 
      using (var entity = new SUIMSEntities1()) 
      { 
       List<Product> products = entity.Products.Include("Category").ToList(); 
       return products;     
      }    
     } 
+2

在SO這是習慣張貼代碼和錯誤消息的文本,文本不screengrabs。 – spender 2012-08-09 23:26:35

回答

4

默認情況下,實體框架(EF)將延遲加載您的類別對象集。因爲您的Category對象集是延遲加載的,所以當稍後引用某個Category的其他代碼時,EF將嘗試加載該集合。但是,在這一點上,您的環境已被處置,導致您看到的錯誤。

你需要做的是強制的背景下急切地加載類別實體設置像這樣:

public static List<Product> GetAllProducts() 
{ 
    List<Product> products = new List<Product>(); 
    using (var entity = new SUIMSEntities1()) 
    { 
     entity.Include("Category"); //force eager loading of Category 
     products = (from p in entity.Products 
        select p).ToList(); 
     return products; 
    }    
} 
+0

你能編輯你的答案來顯示你所描述的內容嗎?準確顯示使用.Include的位置。 – 2012-08-12 23:27:44

+0

我已經給我的回答添加了一些說明。 – Maciej 2012-08-13 15:20:55

2

雖然你是返回一個List<Product>,它會出現訪問類別將造成一個數據庫訪問。問題是您已經處理了訪問數據庫所需的上下文。

相關問題