Crear un objeto de reino
Al crear o actualizar documentos, todas las escrituras deben realizarse en una transacción.
El siguiente código muestra dos métodos para crear un nuevo objeto Realm. En el primer ejemplo, primero creamos el objeto y luego lo añadimos al reino dentro de un MétodoWriteAsync(). En el segundo ejemplo, creamos el documento dentro del WriteAsync
bloque, que devuelve un objeto de reino con el que podemos seguir trabajando.
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" }); } );
Insertar un objeto de reino
Insertar un documento es lo mismo que crear uno nuevo, excepto que se establece el parámetro opcional update en true. En este ejemplo, creamos un nuevo objeto Item con un valor único Id. Luego, insertamos un elemento con el mismo ID, pero con un valor Name diferente. Como se ha establecido el parámetro update en true, el registro existente se actualiza con el nuevo nombre.
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.