繁体   English   中英

Xamarin/C# - 以编程方式为多个表将数据插入 SQLite 数据库?

[英]Xamarin/C# - Insert data into SQLite database programmatically for multiple tables?

我的 Xamarin 应用程序从 API 中提取数据,并将该数据插入到 SQLite 表中。 API 当前定义了 9 个表,因此我的应用程序中有 9 个类与这些表匹配。 我使用了这个问题的已接受答案中的代码片段: Getting all types in a namespace via reflection

下面是我的代码,使用答案中的片段和我正在尝试构建的将插入数据的 foreach 循环。

string nspace = "App.Tables";
            var q = from t in Assembly.GetExecutingAssembly().GetTypes()
                    where t.IsClass && t.Namespace == nspace
                    select t.Name; // Getting list of classes as IEnumerable
            var L = q.ToList(); // Converting to List

            foreach (var name in L) // Inserts data for every class found
            {
                var response = await httpClient.Value.GetStringAsync("http://website.com/api/" + name + "s"); // Substitutes each class name into API url
                var data = JsonConvert.DeserializeObject<List<TableName>>(response); // Deserializes into List
                using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation)) // Opens database connection
                {
                    conn.CreateTable<TableName>(); // Create table
                    conn.DeleteAll<TableName>(); // Delete all old data
                    conn.InsertAll(data); // Inserts new data
                }
            }

我不知道 TableName 应该是什么才能为列表中的每个项目获得正确的 class 。 例如:假设列表包含字符串 Table1、Table2 和 Table3 - 它从 App.Tables 命名空间中获取这些字符串,该命名空间包含三个单独的类,称为 Table1、Table2 和 Table3。 当代码的第一部分获取列表并将其存储为变量 L 时,它应该获取 L 中每个“名称”变量的数据,然后将其插入到匹配表中。 我如何将其引用到表格中?

在我给出答案之前,我想告诉你我不建议通过反射来更新表——表应该包含逻辑上不同的实体,所以批量删除和更新它们有点奇怪。 这是为数不多的情况之一,我永远不会一一键入表格的更新。 但这只是我的两分钱……当然,如果我有一千张桌子,我的意见就不会成立。

这种反射也使您的代码难以跟踪和跟踪- 想想您将如何搜索CreateTable<ExampleClass>()方法的用法? 您将永远无法追溯——或者只能通过巨大的努力——在这段代码中调用它。

所以回答你的问题...

您首先获取方法组,然后根据类型创建它的通用版本。 我认为从Type转换为string对于您要查找的部分来说是不必要的,因为您需要转换回Type

using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation)) {
    MethodInfo nonGenMethodCreate = typeof(SQLiteConnection).GetMethod("CreateTable");
    MethodInfo nonGenMethodDeleteAll = typeof(SQLiteConnection).GetMethod("DeleteAll");
    MethodInfo nonGenMethodInsertAll = typeof(SQLiteConnection).GetMethod("InsertAll");

    foreach(Type t in Assembly.GetExecutingAssembly.GetTypes()) {
        MethodInfo genMethodCreate = nonGenMethodCreate.MakeGenericMethod(t);
        MethodInfo genMethodDeleteAll = nonGenMethodDeleteAll.MakeGenericMethod(t);
        MethodInfo genMethodInsertAll = nonGenMethodInsertAll.MakeGenericMethod(t);

        genMethodCreate.Invoke(conn, null);
        genMethodDeleteAll.Invoke(conn, null);
        genMethodInsertAll.Invoke(conn, new[] { data });

    }
}

暂无
暂无

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

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