Docs 主页 → 开发应用程序 → Atlas Device SDKs
手动定义模式 - .NET SDK
在此页面上
Realm 现为 Atlas Device SDK — 了解详情
当 Realm 处理 Realm 对象时,它会根据类属性为每个类生成一个模式。但是,有时您可能希望手动定义模式,.NET SDK 提供了执行此操作的机制。
重要
继承
所有 Realm 对象都继承自IRealmObject 、 IEmbeddedObject或IAsymmetricObject接口,并且必须声明为 partial
类。
在早于10的 .NET SDK 版本中。 18 。 0 ,对象派生自RealmObject 、 EmbeddedObject或AsymmetricObject基类。这种 Realm 模型定义方法仍然受支持,但不包括可空性注解等新功能。在未来的 SDK 版本中,基类将被弃用。您编写的任何新类都应使用接口,并应考虑迁移现有类。
使用模式属性
您可以使用 RealmConfigurationBase 对象的 Schema 属性来控制模式的定义方式。以下代码示例按从最简单到最复杂的顺序展示了执行此操作的三种方法:自动配置、手动配置以及这两种方法的组合。
// By default, all loaded RealmObject classes are included. // Use the RealmConfiguration when you want to // construct a schema for only specific C# classes: var config = new RealmConfiguration { Schema = new[] { typeof(ClassA), typeof(ClassB) } }; // More advanced: construct the schema manually var manualConfig = new RealmConfiguration { Schema = new RealmSchema.Builder { new Builder("ClassA", ObjectType.EmbeddedObject) { Property.Primitive("Id", RealmValueType.Guid, isPrimaryKey: true), Property.Primitive("LastName", RealmValueType.String, isNullable: true, indexType: IndexType.General) } } }; // Most advanced: mix and match var mixedSchema = new ObjectSchema.Builder(typeof(ClassA)); mixedSchema.Add(Property.FromType<int>("ThisIsNotInTheCSharpClass")); // `mixedSchema` now has all of the properties of the ClassA class // and an extra integer property called "ThisIsNotInTheCSharpClass" var mixedConfig = new RealmConfiguration { Schema = new[] { mixedSchema.Build() } };