标签:
首先引用命名空间
using System.Reflection
了解一下 Assembly 类
// // 摘要: // 表示一个程序集,它是一个可重用、无版本冲突并且可自我描述的公共语言运行时应用程序构造块。 public abstract class Assembly
我们把Model类都约定好放在同一个命名空间下,下面以User类为例:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using SQLite; 7 using Backyard.Common; 8 namespace MyAssembly.Models 9 { 10 [Table("User")] 11 public class User 12 { 13 public User() 14 { 15 } 16 [PrimaryKey,AutoIncrement] 17 public int Id { get; set; } 18 19 [NotNull] 20 public string Pwd { get; set; } 21 public DateTime ResetTime { get; set; } 22 23 public AccountStatus AccountStatus { get; set; } 24 25 } 26 }
我们在看看SQLite CreateTable 方法
/// <summary> /// Executes a "create table if not exists" on the database. It also /// creates any specified indexes on the columns of the table. It uses /// a schema automatically generated from the specified type. You can /// later access this schema by calling GetMapping. /// </summary> /// <param name="ty">Type to reflect to a database table.</param> /// <param name="createFlags">Optional flags allowing implicit PK and indexes based on naming conventions.</param> /// <returns> /// The number of entries added to the database schema. /// </returns> public int CreateTable(Type ty, CreateFlags createFlags = CreateFlags.None)
也就是说 ,当表存在时,调用CreateTable时是不会将已经存在的表覆盖的,表不存在时,则创建数据表。
好了 ,了解了这些 ,我们就可以说说怎么 初始化/添加新的数据表了
//根据数据库地址获取 SQLiteConnection public static SQLiteConnection GetConn() { return new SQLiteConnection(DBSetting.DBPath); } //获取一个程序集对象 通过当前APP的程序集名称 Assembly ass = Assembly.Load(new AssemblyName("MyAssembly")); //获取该程序集中的 公共类型集合 var types = ass.ExportedTypes; using (var conn = GetConn()) { foreach (var t in types) { if (t.Namespace == "MyAssembly.Models") { //这个时候 ,如果数据库不存在 ,就会创建数据库 conn.CreateTable(t); } } }
我们可以在 APP首次启动时 执行一次这个过程 ,不管是首次安装,还是 更新的新版本 ,都可以保证SQLite数据表的完整。
转载原创文章请注明,转载自: 老朱的自留地 » 【WindowsPhone】利用反射初始化和添加 SQLite数据库
【WindowsPhone】利用反射初始化和添加 SQLite数据库
标签:
原文地址:http://www.cnblogs.com/DreamDays/p/4912441.html