SQLite简易版ORMhtml
首先打开项目,使用nuget搜索sqlite-net,以下图:git
下载完成后,咱们会多出两个文件,SQLite.cs和SQLiteAsync.cs。github
咱们新建一个文件夹SQLiteResources,把这俩文件放进去。sql
而后咱们建立两个表实体,以下:数据库
public class Valuation { [PrimaryKey, AutoIncrement] public int Id { get; set; } [Indexed("ValuationStockId2",1)] //索引,注意,该索引在表建立时,会建立,若是索引更名,旧索引依然存在,并未被删除 public int StockId { get; set; } public DateTime Time { get; set; } public decimal Price { get; set; } } public class Stock { [PrimaryKey, AutoIncrement] public int Id { get; set; } public string Symbol { get; set; } }
接下来咱们建立一个SQLiteHelper,用来管理Sqlite数据库,以下:函数
public class SQLiteHelper { public string connstr = Path.Combine(Environment.CurrentDirectory, "User.db");//没有数据库会建立数据库 public SQLiteConnection db; public SQLiteHelper() { db = new SQLiteConnection(connstr); db.CreateTable<Stock>();//表已存在不会重复建立 db.CreateTable<Valuation>(); } public int Add<T>(T model) { return db.Insert(model); } public int Update<T>(T model) { return db.Update(model); } public int Delete<T>(T model) { return db.Update(model); } public List<T> Query<T>(string sql) where T : new() { return db.Query<T>(sql); } public int Execute(string sql) { return db.Execute(sql); } }
到此,咱们的简易版ORM就搭建好了,下面让咱们一块儿试用下这个ORM。工具
首先咱们添加一个项目,SqliteTestConsole。测试
而后在Main函数中写上测试代码以下:lua
static void Main(string[] args) { SQLiteHelper sqliteHelper = new SQLiteHelper(); var list = sqliteHelper.Query<Stock>("select * from Stock"); sqliteHelper.Add(new Valuation() { Price = 100, StockId = 1, Time = DateTime.Now }); var list2 = sqliteHelper.Query<Valuation>("select * from Valuation"); var list3 = sqliteHelper.Query<Valuation>("select * from Valuation INDEXED BY ValuationStockId2 WHERE StockId > 2");//使用索引ValuationStockId2查询 try { sqliteHelper.Execute("drop index ValuationStockId");//删除索引,由于该索引已被删除,因此抛异常 } catch (Exception ex) { } }
而后运行调试,会抛出异常以下:spa
那么咱们到底缺乏什么依赖文件呢?
打开SQLite.cs文件,咱们会发现以下代码:
如上图所示,咱们缺乏了依赖dll—sqlite3.dll。
下面咱们打开sqlite的官网寻找并下载依赖动态库【Sqlite官网下载网址】
由于项目使用x86的Framework4.6.1,因此咱们要找到对应的sqlite版本。
下载完成后,咱们可看到以下文件。
咱们把其中的sqlite3.dll移动到项目的输出目录【X盘\SqliteTestConsole\bin\Debug】下面。
而后咱们运行项目,项目依然提示错误。
这是由于咱们的下载的sqllite3.dll是x86的版本,因此咱们要把Any CPU修改成x86,选择【配置管理器】,以下图:
而后咱们再运行测试项目就能够正常编译经过了。
如今,咱们再使用sqlitebrowser打开咱们建立的User.db查看数据。
sqlitebrowser是一个sqlite的开源管理工具,下载地址:https://github.com/sqlitebrowser/sqlitebrowser。
如图所示,咱们已经成功建立了表,并完成了插入数据操做。
----------------------------------------------------------------------------------------------------
到此SQLite的简易ORM就已经搭建完成了。
代码已经传到Github上了,欢迎你们下载。
Github地址:https://github.com/kiba518/SQLite_net.Helper
----------------------------------------------------------------------------------------------------
注:此文章为原创,欢迎转载,请在文章页面明显位置给出此文连接!
若您以为这篇文章还不错,请点击下方的【推荐】,很是感谢!