Docs 菜单

Docs 主页开发应用程序Atlas Device SDKs

创建数据 - .NET SDK

在此页面上

  • 创建 Realm 对象
  • 更新或插入 Realm 对象

创建或更新文档时,所有写入都必须在事务中进行。

以下代码展示了创建新 Realm 对象的两种方法。在第一个示例中,我们首先创建对象,然后使用WriteAsync()方法将其添加到 Realm。在第二个示例中,我们在 WriteAsync区块中创建文档,该区块会返回一个可供我们进一步使用的 Realm 对象。

var testItem = new Item
{
Name = "Do this thing",
Status = ItemStatus.Open.ToString(),
Assignee = "Aimee"
};
await realm.WriteAsync(() =>
{
realm.Add(testItem);
});
// Or
var testItem2 =
await realm.WriteAsync(() =>
{
return realm.Add<Item>(new Item
{
Name = "Do this thing, too",
Status = ItemStatus.InProgress.ToString(),
Assignee = "Satya"
});
}
);

更新或插入文档与创建新文档相同,只是您将可选的update参数设置为true 。在此示例中,我们创建一个具有唯一Id的新Item对象。然后,我们插入一个具有相同 id 但Name值不同的项目。由于我们已将update参数设置为true ,因此现有记录将更新为新名称。

var id = ObjectId.GenerateNewId();
var item1 = new Item
{
Id = id,
Name = "Defibrillate the Master Oscillator",
Assignee = "Aimee"
};
// Add a new person to the realm. Since nobody with the existing Id
// has been added yet, this person is added.
await realm.WriteAsync(() =>
{
realm.Add(item1, update: true);
});
var item2 = new Item
{
Id = id,
Name = "Fluxify the Turbo Encabulator",
Assignee = "Aimee"
};
// Based on the unique Id field, we have an existing person,
// but with a different name. When `update` is true, you overwrite
// the original entry.
await realm.WriteAsync(() =>
{
realm.Add(item2, update: true);
});
// item1 now has a Name of "Fluxify the Turbo Encabulator"
// and item2 was not added as a new Item in the collection.
← CRUD — .NET SDK