星空网 > 软件开发 > 操作系统

【WindowsPhone】利用反射初始化和添加 SQLite数据库

首先引用命名空间

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 User12   {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数据库

关键词:Windows

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

ST华鼎发布关于全资子公司涉及诉讼的公告:https://www.kjdsnews.com/a/697038.html
跨境大卖巨星科技:公司已完成收购sk tools的各项工作:https://www.kjdsnews.com/a/697039.html
亚马逊、Wish又被点名!不安全产品层出不穷?:https://www.kjdsnews.com/a/697040.html
今年黑五网一大促带给我们了什么?:https://www.kjdsnews.com/a/697041.html
亚洲热潮来袭!日韩&东南亚跨境电商现状全解析【下篇】:https://www.kjdsnews.com/a/697042.html
Anker安克宣布成为全球第一的数码充电品牌:https://www.kjdsnews.com/a/697043.html
永康白云风景区怎么走 白云山风景区怎么去??:https://www.vstour.cn/a/363181.html
2022世界杯门票如何买?:https://www.vstour.cn/a/363182.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流