ObjectDisposedException从Linq返回到SQL查询后
-
13-12-2019 - |
题
我正在使用mvc3与.net 4.0,调用我的创建表单时,我会收到ObjectDisposedException,说对象已被配置。此MVC3 Page语句上的异常OCURS:
@Html.DropDownListFor(model => model.Country, GeneralActivity.GetCountriesMVC("NL"))
.
和调用的方法如下:
IEnumerable<SelectListItem> GetCountriesMVC(string preselectCountryCode)
{
... some error checking code omited for simplicity ...
IEnumerable<SelectListItem> qlist;
using (Data.MyDataContext ctx = new Data.MyDataContext()) {
qlist = from p in ctx.Countries select new SelectListItem {
Text = p.CountryName,
Value = p.CountryCodeId,
Selected = (p.CountryCodeId == preselectCountryCode)
};
}
return qlist;
}
.
在调试期间,我向上执行返回语句,然后它离开并将我带到MVC页面上的调用@HTML语句,并且抛出异常。
Qlist实例在使用语句之外声明并由LINQ查询初始化,因此我不明白为什么它表示对象已被配置。
解决方案
您实际上并不实际执行查询 - 因此,当您尝试访问Qlist时,它会尝试连接到数据库,并且连接关闭。
尝试将查询施放到列表中,以便存储在内存中:
qlist = (from p in ctx.Countries select new SelectListItem {
Text = p.CountryName,
Value = p.CountryCodeId,
Selected = (p.CountryCodeId == preselectCountryCode)
}).ToList();
. 不隶属于 StackOverflow