在.Net中将嵌套对象保存到领域数据库 [英] Saving Nested Objects to Realm Database in .Net

查看:83
本文介绍了在.Net中将嵌套对象保存到领域数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,但是在保存嵌套对象方面遇到很多麻烦.我可以保存父代,但是会得到Realms.Exceptions.RealmObjectManagedByAnotherRealmException并说Cannot start to manage an object with a realm when it's already managed by another realm.我只有一个领域,正在创建一个新对象!

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!

这是父类的样子:

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 );.

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           
}

文档根本没有帮助.

推荐答案

您只需编写一次即可.

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();
}

我已经使用Realm和Xamarin Forms编写了一个应用程序.代码在GitHub上发布, https://github.com/rsatter/PRO-PD/tree/master/PRO-PD .

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.

这篇关于在.Net中将嵌套对象保存到领域数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆