Xamarin/C# - 为多个表以编程方式将数据插入 SQLite 数据库? [英] Xamarin/C# - Insert data into SQLite database programmatically for multiple tables?

查看:26
本文介绍了Xamarin/C# - 为多个表以编程方式将数据插入 SQLite 数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Xamarin 应用从 API 中提取数据并将该数据插入到 SQLite 表中.API 当前定义了 9 个表,因此我的应用程序中有 9 个与这些表匹配的类.我使用了这个问题接受的答案中的代码片段:通过反射获取命名空间中的所有类型

My Xamarin app pulls data from an API and inserts that data into a SQLite table. The API currently has 9 tables defined, and as such there are 9 classes in my app that match those tables. I used the code snippet from this question's accepted answer: Getting all types in a namespace via reflection

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

Below is my code, using the snippet from the answer and the foreach loop I'm trying to build that'll insert the data.

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 应该是什么,以便为列表中的每个项目获得正确的类.例如:假设列表包含字符串 Table1、Table2 和 Table3 - 它从 App.Tables 命名空间获取这些字符串,其中包含三个独立的类,称为 Table1、Table2 和 Table3.当代码的第一部分获取列表并将其存储为变量 L 时,它应该获取 L 中每个名称"变量的数据,然后将其插入匹配表中.我如何将其引用到表格中?

I don't know what TableName should be in order to get the correct class for each item on the list. For example: say the list contained the strings Table1, Table2, and Table3 - it got those strings from the App.Tables namespace which contains three separate classes called Table1, Table2, and Table3. When the first part of the code gets the list and stores it as the variable L, it should get the data for each "name" variable in L and then insert it into the matching table. How do I refer it to the table?

推荐答案

在我给出答案之前,我想告诉你,我不建议通过反射更新表格 - 表格应包含逻辑上不同的实体,因此批量删除和更新它们是有点奇怪.这是我永远不会发生的少数事件之一解决一项一项地键入表的更新.但那些是只是我的两分钱......当然,如果我有一千张桌子,我的意见受不了.

Before I would give my answer, I would like to tell you that I do not recommend updating tables via reflection - tables should contain logically distinct entities, so batch deleting and updating them is kinda weird. This is one of those few occurrences where I would never work around typing the updates of the tables one by one. But those are just my two cents... Of course if I had a thousand tables my opinion would not stand.

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

This kind of reflection also makes your code hard to follow and trace - think about how you will search for usages of the CreateTable<ExampleClass>() method? You will never trace it back - or only via great efforts - that you called it in this piece of code.

所以回答你的问题...

So to answer your question...

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

You first get the method group, then create a generic version of it based on the type. I think converting from Type to string is unnecessary for the part you're looking for, since you need to convert back to 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 });

    }
}

这篇关于Xamarin/C# - 为多个表以编程方式将数据插入 SQLite 数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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