我对领域很陌生,我在获取嵌套对象时遇到了很多麻烦。我可以保存父母,但我得Realms.Exceptions.RealmObjectManagedByAnotherRealmException
说Cannot start to manage an object with a realm when it's already managed by another realm
。我只有一个领域而且我正在创建一个新对象!
这是父类的样子:
public class Transaction : RealmObject
{
[PrimaryKey]
public string ID { get; set; } = Guid.NewGuid().ToString();
...
public IList<TransactionDetails> Rows { get; }
}
这是孩子:
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; }
...
}
在我尝试保存对象realm = Realm.GetInstance( config );
的类的构造函数中。
这是我最近尝试在单独的写入事务中编写详细信息的尝试,但它没有用。
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
}
documentation根本没用。
答案 0 :(得分:1)
你只需要写一次。
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 ) );
最好不要在交易中包装它。
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();
}
我使用Realm和Xamarin Forms编写了一个应用程序。代码在GitHub上发布,https://github.com/rsatter/PRO-PD/tree/master/PRO-PD。