VB.NET中Realm数据库打开及IList属性定义问题求助
问题描述
作为Realm新手,尝试使用官方提供的demo-v24.realm数据库,编写VB.NET代码配置RealmConfiguration并打开数据库时遇到问题:将C#的RealmObject子类中IList类型属性转换为VB.NET定义后,抛出Realms.Exceptions.RealmMigrationNeededException,提示“Property 'RealmTestClass1.arrayReference' has been removed”。尝试多种属性定义方式均无效,现咨询两个问题:
- 如何正确将C#中的IList类型引用属性转换为VB.NET定义?
- 是否存在无需预先知晓Schema即可打开读取Realm文件的简便方法?
现有代码
配置与读取代码
Dim r1 as Realm Dim config As RealmConfiguration config = New RealmConfiguration("demo-v24.realm") config.Schema = New Type() {GetType(RealmTestClass0), GetType(RealmTestClass1), GetType(RealmTestClass2)} config.SchemaVersion = 1 config.IsDynamic = True 'open database r1 = Realm.GetInstance(config) 'read from database Dim people As String = r1.All(Of RealmTestClass0)().Where(Function(p) p.IntegerValue > 0 And p.IntegerValue < 100000).ToString
VB.NET类定义(错误版本)
Public Class RealmTestClass1 Inherits RealmObject ... <MapTo("arrayReference")> Public ReadOnly Property ArrayReference As IList(Of RealmTestClass0) Get Return Nothing 'GetList(Of RealmTestClass0)("arrayReference") // does not work! End Get End Property End Class
C#原类定义
public class RealmTestClass1 : RealmObject { ... [MapTo("arrayReference")] public IList<RealmTestClass0> ArrayReference { get; } }
解答
1. 正确转换C# IList属性到VB.NET的方法
在VB.NET中定义Realm的只读集合属性时,不能返回Nothing,必须通过GetList(Of T)方法返回Realm托管的集合实例,否则Realm会判定该属性已被移除,触发迁移异常。
修正后的VB.NET类定义:
Public Class RealmTestClass1 Inherits RealmObject ... <MapTo("arrayReference")> Public ReadOnly Property ArrayReference As IList(Of RealmTestClass0) Get Return Me.GetList(Of RealmTestClass0)("arrayReference") End Get End Property End Class
注意事项:
- 必须调用
Me.GetList获取Realm托管的集合,不能手动实例化或返回空值 MapTo特性的字段名要和数据库中对应字段完全匹配- 确保
RealmTestClass0已正确定义为RealmObject子类 - 配置代码中同时设置
Schema和IsDynamic = True会冲突,使用强类型实体类时需将IsDynamic设为False
2. 无需预定义Schema读取Realm的方法
可以使用Realm的动态模式(Dynamic Realm),无需预先编写实体类,直接通过字段名访问数据:
动态模式示例代码
Dim config As New RealmConfiguration("demo-v24.realm") config.IsDynamic = True ' 启用动态模式,无需指定Schema config.SchemaVersion = 1 ' 匹配数据库的实际版本 Dim r1 = Realm.GetInstance(config) ' 动态获取集合,直接使用类名字符串 Dim people = r1.All("RealmTestClass0").Where(Function(p) p.IntegerValue > 0 And p.IntegerValue < 100000) ' 遍历数据,通过属性名访问字段 For Each item In people Console.WriteLine($"ID: {item.Id}, Value: {item.IntegerValue}") Next
动态模式特点:
- 无需编写
RealmObject子类,直接通过字符串访问集合和字段 - 无类型安全保障,字段名拼写错误会在运行时抛出异常
- 适合快速查看未知Schema的Realm数据库内容
内容的提问来源于stack exchange,提问作者Hawk78
相关产品推荐
相关产品推荐

