作業流程:
我有一個帶有兩種形式的 winform 應用程式,在第一種形式中我查詢 aliteDB并使用檢索到的資料操作塊內的IEnumerable<T>一個實體。using
IEnumerable<student> searchResult;
using(var db = new LiteDatabase(@"C:\Temp\MyData.db"))
{
var col = db.GetCollection<student>("students");
col.EnsureIndex(x => x.contact.phone);
searchResult = col.Find(x => x.contact.phone == "123456789");
}
Form2 frm2 = new Form2();
Form2.profileData = searchResult.AtElement(index);
問題:
然后,我需要向searchResult<student>第二個表單發送一個元素以顯示用戶,正如您在上面代碼的最后 2 行中看到的那樣。
但由于它在using塊內,我得到System.ObjectDisposedException.
資料型別和例外:
studentCollection.Find()::
例外:
加法
:
searchResult

What I already though of as possible way is:
Override and nullify existing dispose() method then call my own implemented method after I'm done; Which is basically equals to not having a using block, except that I don't have to take care of disposing other objects in above using block, but only searchResult<student>.
P.S: I'm newbie at whole thing, appreciate the help and explanation
uj5u.com熱心網友回復:
我不熟悉 LiteDb,但我認為它會回傳資料庫的代理物件。因此,當資料庫被處置時,代理物件不再可用。
避免該問題的簡單方法是.ToList()在.Find(...). 這會將代理串列轉換為List<T>記憶體中的實際串列,并且可以在資料庫處理后使用。student串列中的物件也可能是代理,如果是這種情況,這將失敗。
如果是這種情況,您要么需要找到某種方法使資料庫回傳真實的非代理物件,要么將資料庫的生命周期延長到比表單的生命周期更長,例如
IList<student> myIList;
using(var db = new LiteDatabase(@"C:\Temp\MyData.db"))
{
var col = db.GetCollection<student>("students");
col.EnsureIndex(x => x.contact.phone);
myIList = col.Find(x => x.contact.phone == "123456789");
using(var frm2 = new Form2()){
frm2.profileData = myIList.AtElement(index);
frm2.ShowDialog(this);
}
}
注意 的用法.ShowDialog,這將阻塞直到第二個表單關閉。這不是絕對必要的,但它使管理資料庫的生命周期變得更加容易。
uj5u.com熱心網友回復:
您需要在退出 using 塊之前訪問該元素。
using(var db = new LiteDatabase(@"C:\Temp\MyData.db"))
{
var col = db.GetCollection<student>("students");
col.EnsureIndex(x => x.contact.phone);
var searchResult = col.Find(x => x.contact.phone == "123456789");
Form2 frm2 = new Form2();
Form2.profileData = searchResult.AtElement(index);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/450317.html
標籤:c# winforms idisposable objectdisposedexception litedb
上一篇:在.NETcore3.1中找不到MenuItem和ContextMenuItem
下一篇:FilePath錯誤/不支持
