我正在尝试从WinForm dotnet应用程序中的领域数据库中删除对象,但是我的代码给了我这个错误
引发的异常:“ Realms.Exceptions.RealmInvalidObjectException”在 Realm.dll类型的异常 Realm.dll中发生了'Realms.Exceptions.RealmInvalidObjectException' 但未在用户代码中处理试图访问分离的行
Realm realm;
IQueryable<RObj> items;
public Form1()
{
InitializeComponent();
var config = new RealmConfiguration("DB.realm");
config.ShouldDeleteIfMigrationNeeded = true;
realm = Realm.GetInstance(config);
//WriteRealmTest();
}
private void Form1_Load(object sender, EventArgs e)
{
items = realm.All<RObj>();
listboxMain.DisplayMember = "title";
listboxMain.ValueMember = "id";
BindingSource bs = new BindingSource();
bs.DataSource = items;
listboxMain.DataSource = bs;
}
private void listboxMain_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
int index = listboxMain.SelectedIndex;
if (index < 0) { return; }
RObj item = items.ElementAt(index);
if (!item.IsValid)
return;
using (var trans = realm.BeginWrite())
{
realm.Remove(item);
trans.Commit(); //when this line is commented, no error is raised
}
}
}
答案 0 :(得分:0)
我发现了问题,这对于面临相同问题的任何人都可以作为参考
我必须先从BindingSource
中删除该项目,然后再将其从领域数据库中删除
在bs.RemoveAt(index)
之前添加using (var trans = realm.BeginWrite())
解决了该问题