简体   繁体   English

如何在Xamarin中将行从Web(JSON)批量插入领域数据库

[英]How to bulk insert rows into realm database from web (JSON) in Xamarin

This is my very first attempt to work with Xamarin studio with Realm (to make app for both iOS and Android) and I am stuck at this situation since last 24 hours. 这是我与Xamarin Studio和Realm一起工作(为iOS和Android制作应用程序)的第一次尝试,而自从过去24小时以来,我一直处于这种情况。

My online database-table has 30,000 rows. 我的在线数据库表有30,000行。 Earlier when I used to work in Android studio, I used to import those rows in app's 1st run with the help of JSON, GSON and insert into SQLite db. 以前,当我以前在Android Studio中工作时,我曾借助JSON,GSON将这些行导入应用程序的第一次运行中,并插入到SQLite数据库中。

But I am unable to do so in Realm & Xamarin. 但是我无法在Realm和Xamarin中做到这一点。 I know, I have not provided any code snippet (my effort), but honestly even after searching a lot about this, I couldn't find how should I proceed? 我知道,我没有提供任何代码片段(我的努力),但是老实说,即使在搜索了很多内容之后,我仍然找不到应该怎么做?

I've already answered that in the Github issue , but in case someone else stumbles across it, the best way to do that without blocking the UI thread, is to use the Realm.WriteAsync API. 我已经在Github问题中回答了这个问题 ,但是如果有人偶然发现它,最好的方法是使用Realm.WriteAsync API,而不阻塞UI线程。 Basically, you'll do something like: 基本上,您将执行以下操作:

var items = await service.GetAllItems();
// I assume items are already deserialized RealmObject-s
var realm = Realm.GetInstance();
await realm.WriteAsync(r =>
{
    foreach (var item in items)
    {
        r.Manage(item);
    }
}
/* Data is loaded, show message or process it in other ways */

One thing to note is that within the WriteAsync lambda, we're using the r instance and not the original realm one. 需要注意的一件事是,在WriteAsync lambda中,我们使用的是r实例,而不是原始realm The reason is that because realms are not thread safe and the asynchronous write will happen on another thread, so it implicitly creates another instance and passes it as an argument of the action parameter. 原因是因为领域不是线程安全的,并且异步写入将在另一个线程上进行,所以它隐式创建另一个实例并将其作为action参数的参数传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM