因为在仿真建模的过程中,希望把运行过程传递给数据可视化的控制台显示出来,约定了以离线SQLite文件最为我们的数据接口。所以考虑到用ServiceStack.OrmLite来写数据到SQLite中。
步骤如下:
- 在NuGet中安装Service Stack.OrmLite和ServiceStack.OrmLite.Sqlite包
- 创建数据结构和表的映射关系
class Foo
{
[AutoIncrement]
public int Id { get; set; }
[CustomField("INT")]
public int Idx { get; set; }
[CustomField("CHAR(20)")]
public string? Name { get; set; }
[CustomField("CHAR(20)")]
public string? CharColumn { get; set; }
[CustomField("DECIMAL(18,4)")]
public decimal? DecimalColumn { get; set; }
public void PrintDump()
{
Console.WriteLine($"Id={Id}, Name={Name}");
}
}
- 创建数据库访问接口
class DvSQLite
{
public static string SqliteFileDb = String.Format($"~/AppData/SQLiteDbTest.sqlite").MapAbsolutePath();
static OrmLiteConnectionFactory dbFactory = new OrmLiteConnectionFactory(SqliteFileDb, SqliteDialect.Provider);
private IDbConnection _db;
public DvSQLite()
{
_db = dbFactory.Open();
_db.CreateTable<Foo>(true);
}
public void InsertFoo(Foo foo)
{
_db.Insert<Foo>(foo);
}
public Foo SelectFoo(int idx)
{
var result = _db.SingleById<Foo>(idx);
result.PrintDump();
}
}
- 使用
private static DvSQLite _dvSQLite = new DvSQLite();
_dvSQLite.InsertFoo(new Foo{Idx = 1, Name = "name"});
_dvSQLite.SelectFoo(1);
|