using SqlSugar;
using System;
using System.Data.SQLite;
using System.Linq;
namespace IStation.DAL
{
public class BasicDb
{
///
/// 初始数据库
///
///
///
///
///
public static bool InitTables(long projectId, bool backup = false, int stringDefaultLength = 250)
{
var db = GetDb(projectId);
if (db == null)
return false;
Type[] types = new Type[] {
typeof(Entity.SignalType),
typeof(Entity.SignalTypeGroup),
typeof(Entity.ElecPrice),
typeof(Entity.Station),
typeof(Entity.Equipment),
typeof(Entity.EquipmentGroup),
typeof(Entity.EquipmentMonitorMapping),
typeof(Entity.PumpCurve),
typeof(Entity.PumpCurveMapping),
typeof(Entity.PumpSpeedCurve),
typeof(Entity.MonitorPoint),
typeof(Entity.MonitorPointGroup),
typeof(Entity.Signal),
};
//Db.CodeFirst.SetStringDefaultLength(StringDefaultLength);
db.DbMaintenance.CreateDatabase();
if (backup)
{
db.CodeFirst.BackupTable().InitTables(types);
}
else
{
db.CodeFirst.InitTables(types);
}
return true;
}
private static SqlSugarClient GetDb(long projectId)
{
if (projectId < 1)
return default;
var dbName = Settings.File.BasicDB;
var filePath = $"{FileHelper.GetProjectFolder(projectId)}\\{dbName}";
if (!System.IO.File.Exists(filePath))
{
try
{
SQLiteConnection.CreateFile(filePath);
}
catch (Exception ex)
{
var errMsg = $"{dbName}文件不存在!Path:{filePath}\r\n{ex.Message}";
//LogHelper.Debug(errMsg);
throw new Exception(errMsg);
}
}
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;
}
}
};
var 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();
};
return db;
}
}
}