【问题标题】:Array of string with Realm database .NET sdk带有 Realm 数据库 .NET sdk 的字符串数组
【发布时间】:2021-09-28 12:55:47
【问题描述】:

我的领域架构将属性定义为字符串数组。我在我的 .NET 模型中将此属性添加为RealmList<string>,但这始终是一个空列表。我也尝试使用IList<string>,但我有一个null 值。

有人已经尝试映射原始列表而不是 EmbeddedObjectRealmObject 列表?

我的架构:

{
  "title": "simple",
  "bsonType": "object",
  "properties": {
    "_id": {
      "bsonType": "objectId"
    },
    "_partition": {
      "bsonType": "string"
    },
    "name": {
      "bsonType": "string"
    },
    "hashtags": {
      "bsonType": "array",
      "items": {
        "bsonType": "string"
      }
    }
  },
  "required": [
    "_id",
    "_partition",
    "name"
  ]
}

存储的数据示例

{
    "_id": {
        "$oid": "6151a0eb49d3cbc1b3795579"
    },
    "_partition": "Part001",
    "name": "First obj",
    "hashtags": ["001", "0003"]
}

我的 .NET 模型:

[MapTo("simple")]
public class Simple : RealmObject
{
  [PrimaryKey]
  [MapTo("_id")]
  public ObjectId Id { get; set; } = ObjectId.GenerateNewId();

  [Required]
  [MapTo("_partition")]
  public string Partition { get; set; }

  [Required]
  [MapTo("name")]
  public string Name { get; set; }

  [MapTo("hashtags")]
  public RealmList<string> Hashtags { get; }
}

加载数据的.NET代码

var app = App.Create("my-realm");

var user = await app.LogInAsync(Credentials.EmailPassword("", ""));

var configuration = new SyncConfiguration("Part001", user)
{
  ObjectClasses = new[] { typeof(Simple) }
};

var realm = await Realm.GetInstanceAsync(configuration);
await realm.GetSession().WaitForDownloadAsync();
await realm.GetSession().WaitForUploadAsync();

var simples = realm.All<Simple>().ToList();

【问题讨论】:

  • 也许重新阅读有关List 对象的文档会有所帮助。它说 - 通过定义 IList 类型的仅 getter 属性来创建一个 List 集合。 - 然后 - Local-only Realm Databases 支持可为空(可选)值的集合,但 Sync 不支持。- 这意味着文档的这一部分 - 添加 [Required] 属性,如果list 包含可为空的引用类型,例如 string 或 byte[] - 是相关的

标签: .net mongodb realm


【解决方案1】:

当我对数组使用唯一约束时,我将其解决为使用 IList 和 ISet。

[MapTo("simple")]
public class Simple : RealmObject
{
  [PrimaryKey]
  [MapTo("_id")]
  public ObjectId Id { get; set; } = ObjectId.GenerateNewId();

  [Required]
  [MapTo("_partition")]
  public string Partition { get; set; }

  [Required]
  [MapTo("name")]
  public string Name { get; set; }

  [MapTo("hashtags")]
  public IList<string> Hashtags { get; }

  // If I use "uniqueItems": true in my schema
  // "hashtags": {
  //  "bsonType": "array",
  //  "uniqueItems": true,
  //  "items": {
  //    "bsonType": "string"
  //  }
  // }
  // [Required]
  // [MapTo("hashtags")]
  // public ISet<string> Hashtags { get; }
}

【讨论】:

    猜你喜欢
    • 2018-04-25
    • 2021-08-25
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 2020-03-30
    • 2015-09-19
    • 1970-01-01
    相关资源
    最近更新 更多