First reference namespace
using System.Reflection
Check out the Assembly class
// // Summary: // represents an assembly, which is a reusable, version-free, and self-describing common language runtime application building block. Publicabstractclass Assembly
We have agreed on the model class to be placed under the same namespace, following the user class as an example:
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSystem.Threading.Tasks;6 usingSQLite;7 usingBackyard.common;8 namespaceMyassembly.models9 {Ten[Table ("User")] One Public classUser A { - PublicUser () - { the } - [Primarykey,autoincrement] - Public intId {Get;Set; } - + [Notnull] - Public stringPWD {Get;Set; } + PublicDateTime Resettime {Get;Set; } A at PublicAccountstatus Accountstatus {Get;Set; } - - } -}
We're looking at the SQLite createtable method.
/// <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 intCreateTable (Type ty, createflags createflags = createflags.none)
That is, when the table is present, when the call to CreateTable is not overwritten by the table that already exists and the table does not exist, the data table is created.
Well, knowing this, we can talk about how to initialize/Add a new data table.
//get sqliteconnection based on database address Public Staticsqliteconnection Getconn () {return Newsqliteconnection (Dbsetting.dbpath);}//Gets an assembly object through the current app's assembly nameAssembly-Assembly.Load (NewAssemblyName ("myassembly"));//gets the collection of public types in the AssemblyvarTypes =The . Exportedtypes;using(varconn =Getconn ()) { foreach(varTinchtypes) { if(T.namespace = ="Myassembly.models") { //this time, if the database does not exist, the database will be createdConn. CreateTable (t); } }}
We can do this one time at the first launch of the app, whether it's a first-time installation or a new version of the update, which guarantees the integrity of the SQLite data sheet.
Reprint original article Please indicate, reprint from: Lao Zhu's private plots» "WindowsPhone" Initialize and add SQLite database with Reflection
"WindowsPhone" Initializes and adds a SQLite database with reflection