在.Net中将嵌套对象保存到领域数据库

编程入门 行业动态 更新时间:2024-10-28 18:23:53
本文介绍了在.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上发布, github/rsatter/PRO-PD/tree/master/PRO-PD .

I have written an app using Realm and Xamarin Forms. Code is released on GitHub, github/rsatter/PRO-PD/tree/master/PRO-PD.

更多推荐

在.Net中将嵌套对象保存到领域数据库

本文发布于:2023-11-26 05:53:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632894.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   中将   对象   领域   数据库

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!