I'm new to realm and I'm having a lot of trouble getting a nested object to save. I can save the parent, but I get a Realms.Exceptions.RealmObjectManagedByAnotherRealmException saying Cannot start to manage an object with a realm when it's already managed by another realm. I only have one realm and I'm creating a new object!
This is what the parent class looks like:
public class Transaction : RealmObject
{
[PrimaryKey]
public string ID { get; set; } = Guid.NewGuid().ToString();
...
public IList<TransactionDetails> Rows { get; }
}
and here is the child:
public class TransactionDetails : RealmObject
{
[PrimaryKey]
public string ID { get; set; } = Guid.NewGuid().ToString();
public Account Account { get; set; } = new Account();
public double Amount { get; set; }
...
}
In the constructor for the class where I'm trying to save the object I have realm = Realm.GetInstance( config );.
This is my latest attempt in which I tried to write the details in a separate write transaction but it didn't work.
var transaction = new Models.Transaction();
...
realm.Write( () => realm.Add( transaction, update: true ) );
foreach ( var details in Trans.Rows )
{
var row = new TransactionDetails();
...
//realm.Add( details );
//realm.Write( () => realm.Add( details ) );
realm.Write( () => transaction.Rows.Add( details ) ); // Error here every time
}
The documentation wasn't helpful at all.
You only need to do the write once.
var transaction = new Models.Transaction();
...
foreach ( var details in Trans.Rows )
{
var row = new TransactionDetails();
...
transaction.Rows.Add( details ); // Error here every time
}
realm.Write( () => realm.Add( transaction, update: true ) );
You would be better off wrapping this in a transaction.
using (Transaction _transaction = realm.BeginWrite())
{
var trans = new Models.Transaction();
...
realm.Add(trans);
foreach ( var details in Trans.Rows )
{
var row = new TransactionDetails();
...
trans.Rows.Add( details ); // Error here every time
}
_transaction.Commit();
}
I have written an app using Realm and Xamarin Forms. Code is released on GitHub, https://github.com/rsatter/PRO-PD/tree/master/PRO-PD.
来源:https://stackoverflow.com/questions/47944439/saving-nested-objects-to-realm-database-in-net