2012-07-02 319 views
0

因此,我正在學習製作一個非常簡單的MVC + EF頁面。它應該將一個國家列表放入dropDownList中。我碰到這個錯誤:EF4 DBContext和MVC3。 ObjectContext實例已被處置,不能再用於需要連接的操作

ObjectDisposedException被用戶代碼未處理:ObjectContext實例已被處置,不能再用於需要連接的操作。

我以爲我知道,DBContext將被處置,所以我拉起字符串和數組字符串[]中的值。爲什麼我仍然遇到這個問題?

View.cshtml ...

<select id="register-country"> 
    @foreach (var country in ViewBag.Countries) { //******** ERROR HERE ******** 
     <option value="@country[0]">@country[1]</option> 
    } 
</select> 

Controller.cs ...

public virtual ActionResult RegisterDialogPartial() { 
    var csm = new CountryStateModelRepository(); 
    ViewBag.Countries = csm.GetCountries(); 
    return PartialView(MVC.Shared.Views._RegisterDialogPartial); 
} 

DataAccessLayer ...

public class CountryStateModelRepository { 
    public IQueryable<string[]> GetCountries() { 
     using (var db = new CountryStateModelContainer()) { 
      return db.Country.Select(r => new string[] { r.CountryISO3, r.CountryName }); 
     } 
    } 
    public IQueryable<string> GetCountryStates(string countryISO3) { 
     using (var db = new CountryStateModelContainer()) { 
      return db.CountryState.Filter(r => r.CountryISO3 == countryISO3.ToUpper()).Select(r=>r.CountryISO3).AsQueryable(); 
     } 
    } 
} 
+1

向延遲執行說聲問候。如果返回'IQueryable',則不能處理上下文。您必須在通過調用例如'ToList'來處理上下文之前執行查詢。 –

回答

2

我非常肯定,實體框架和LINQ的工作,使查詢不會執行,直到枚舉的值(在這種情況下,直到你的看法,這不會發生)。如果你希望枚舉函數調用時的值,請修改你的方法,如下所示:

return db.Country.Select(r => new string[] { r.CountryISO3, r.CountryName }).AsEnumerable(); 
+0

所以,我試圖添加.AsEnumerable()和.AsQueryable()和.ToList()。另外,在edmx屬性中關閉延遲加載的東西。他們仍然都會返回相同的錯誤。似乎沒有工作? – Tom

+0

如果不親自構建項目,我不能確切地說出了什麼問題,但如果您仍然遇到錯誤,我會嘗試兩件事。其一,嘗試刪除'using'並顯式創建一個datacontext對象,並明確地將它的值賦給一個局部變量,然後返回它;或者,可能只是您需要清理/重建項目。 當你做AsEnumerable時,你是否也設置函數調用的返回類型爲IEnumerable? – Richthofen

+0

1.是的,我將返回類型設置爲每個正確的相應的返回類型。 2.主代碼幾乎在這裏,除了有更多的代碼,你可以看到它返回一個局部視圖,當有一個Ajax調用時,它返回到一個JQuery對話框。也就是說,這個局部視圖在整個頁面完成渲染後會單獨調用,但我認爲這與EF沒有關係?除此之外沒有更多的代碼功能。 – Tom

相關問題