using SqlSugar;
|
using System;
|
using System.Data.SQLite;
|
using System.IO;
|
using System.Linq;
|
|
namespace IStation.ChEr.DAL
|
{
|
public class MainDbContext
|
{
|
public MainDbContext()
|
{
|
//var dbName = "Db4MainV1.db";
|
var dbName = Settings.SQLite.MainDbName;
|
var filePath = $"{Settings.File.LocalDataDirectory}\\{dbName}";
|
if (!System.IO.File.Exists(filePath))
|
{
|
try
|
{
|
if (!Directory.Exists(Settings.File.LocalDataDirectory))
|
{
|
Directory.CreateDirectory(Settings.File.LocalDataDirectory);
|
}
|
SQLiteConnection.CreateFile(filePath);
|
}
|
catch (Exception ex)
|
{
|
throw new System.Exception($"{dbName}文件不存在!Path:{filePath}\r\n{ex.Message}");
|
}
|
}
|
|
var config = new ConnectionConfig();
|
config.ConnectionString = $"DataSource={filePath}";
|
config.IsAutoCloseConnection = true;
|
config.DbType = SqlSugar.DbType.Sqlite;
|
config.ConfigureExternalServices = new ConfigureExternalServices()
|
{
|
EntityService = (property, column) =>
|
{
|
//除主键外都可空
|
if (!column.IsPrimarykey)
|
{
|
column.IsNullable = true;
|
}
|
}
|
};
|
|
Db = new SqlSugarClient(config);
|
Db.Aop.OnLogExecuting = (sql, pars) =>
|
{
|
Console.WriteLine(sql + "\r\n" + Db.Utilities.SerializeObject
|
(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
|
Console.WriteLine();
|
};
|
}
|
|
public SqlSugarClient Db { get; set; }
|
|
public void InitTables(bool Backup = false, int StringDefaultLength = 250)
|
{
|
var simple = new SimpleClient<Entity.WaterPredict>();//IsNullable
|
|
Type[] types = new Type[] {
|
typeof(Entity.WaterPredict)
|
};
|
|
//Db.CodeFirst.SetStringDefaultLength(StringDefaultLength);
|
Db.DbMaintenance.CreateDatabase();
|
if (Backup)
|
{
|
Db.CodeFirst.BackupTable().InitTables(types);
|
}
|
else
|
{
|
Db.CodeFirst.InitTables(types);
|
}
|
}
|
|
// public SimpleClient<Entity.Pump> pumpDb { get { return new SimpleClient<Entity.Pump>(Db); } }
|
//public SimpleClient<Schools> schoolDb { get { return new SimpleClient<Schools>(Db); } }
|
}
|
}
|