简体   繁体   English

在SQLite数据库中保存接口项列表

[英]Save a list of interface items in a SQLite database

I'm developing an app at the moment. 我正在开发一款应用程序。 To save the items I want to use an SQLite database. 要保存我想要使用SQLite数据库的项目。 The implementation works in general (using the SQLite.Net-PCL library), however I'm failing at saving a collection of items that inherit from a interface called IItem . 实现工作一般(使用SQLite.Net-PCL库),但是我无法保存从名为IItem的接口继承的项集合。

It works the following way: 它的工作方式如下:

var conn = new SQLiteConnection(new SQLitePlatformWinRT(), "myapp.db");

// Code that creates the `items` list.

foreach (IItem item in items)
    conn.InsertOrReplace(item, typeof(IItem));

But to reduce the overhead, I prefer it to do it this way: 但是为了减少开销,我更喜欢这样做:

conn.InsertOrReplaceAll(items, typeof(List<IItem>));

Sadly this doesn't work due to an System.Reflection.TargetException . 遗憾的是,由于System.Reflection.TargetException这不起作用。

Any ideas to get the latter one working, primary because of perf reasons? 有什么想法让后者工作,主要是因为性能原因?

The problem here is that you are using wrong type as the parameter in InsertOrReplaceAll method. 这里的问题是您使用错误的类型作为InsertOrReplaceAll方法中的参数。 The objType in this method represents the type of the single item , you can use this method like following: 此方法中的objType表示单个项类型 ,您可以使用以下方法:

conn.InsertOrReplaceAll(items, typeof(IItem));

To see this clearly, we can look at the source code on GitHub : 为了清楚地看到这一点,我们可以查看GitHub上源代码

public int InsertOrReplaceAll(IEnumerable objects, Type objType)
{
    var c = 0;
    RunInTransaction(() =>
    {
        foreach (var r in objects)
        {
            c += InsertOrReplace(r, objType);
        }
    });
    return c;
}

From the source code, we can find in this method, it also calls InsertOrReplace(object obj, Type objType) method. 从源代码中我们可以发现,在这个方法中,它还调用了InsertOrReplace(object obj, Type objType)方法。 Besides, there is another overload method of InsertOrReplaceAll . 此外,还有另一种InsertOrReplaceAll重载方法。

public int InsertOrReplaceAll(IEnumerable objects);

With this method, we can do not care about the type issue. 使用这种方法,我们可以不关心类型问题。

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

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