如何在C#中借助文本文件创建SQLite数据库表
动态创建SQLite数据库表(从文本文件读取模型类名)
问题背景
需要在C#中根据文本文件里的模型类名,动态调用SQLite的CreateTable<T>方法创建数据库表。已成功读取文件中的类名字符串,但因泛型方法需要编译时确定类型,无法直接使用字符串调用。
文本文件示例
Customer CustomerAgent CustomerAddress
模型类示例
[Table("Customer")] public class Customer { [AutoIncrement, PrimaryKey, Unique] public int UniqueId { get; set; } public int AccountNumber { get; set; } }
已实现的读取代码
try { string filePath = "models.txt"; string[] modelNames = File.ReadAllLines(filePath); foreach (string modelName in modelNames) { Console.WriteLine($"Creating table for model: {modelName}"); // 此处需创建数据库表,常规写法为:SqliteConnection.CreateTable<ClassName>(); } } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); }
解决方案
核心思路是通过反射获取模型类的Type对象,再动态构造并调用泛型的CreateTable<T>方法。
完整实现代码
using System.Reflection; using SQLite; // 初始化SQLite连接 using var dbConnection = new SQLiteConnection("Data Source=your_database.db"); dbConnection.Open(); try { string filePath = "models.txt"; string[] modelNames = File.ReadAllLines(filePath); // 替换为你的模型类实际所在的命名空间 string modelNamespace = "YourApp.Models"; foreach (string modelName in modelNames) { // 拼接完整的类型名称(命名空间 + 类名) string fullTypeName = $"{modelNamespace}.{modelName}"; Type modelType = Type.GetType(fullTypeName); if (modelType == null) { Console.WriteLine($"警告:未找到模型类 {modelName}"); continue; } Console.WriteLine($"正在创建表:{modelName}"); // 获取CreateTable方法的泛型定义 MethodInfo createTableMethod = typeof(SQLiteConnection).GetMethod("CreateTable", Type.EmptyTypes); // 构造对应模型类型的泛型方法 MethodInfo genericMethod = createTableMethod.MakeGenericMethod(modelType); // 执行创建表操作 genericMethod.Invoke(dbConnection, null); } } catch (Exception ex) { Console.WriteLine($"错误:{ex.Message}"); } finally { dbConnection.Close(); }
关键说明
- 命名空间匹配:必须确保
modelNamespace与模型类实际所在的命名空间一致,否则无法找到类型。如果模型类在根命名空间,可直接使用modelName作为类型名,但推荐显式指定命名空间避免冲突。 - 外部程序集的模型类:如果模型类在单独的程序集(如类库)中,需要先加载程序集再获取类型:
Assembly modelAssembly = Assembly.LoadFrom("YourModelLibrary.dll"); Type modelType = modelAssembly.GetType($"{modelNamespace}.{modelName}"); - 异常处理:增加了类型不存在的判断,避免因文件中存在无效类名导致程序崩溃。
内容的提问来源于stack exchange,提问作者ckoder
相关产品推荐
相关产品推荐

