using System.Data.SQLite;
|
|
namespace IStation.DAL
|
{
|
public class DbInitial
|
{
|
|
private static string _dbName = "Db4Schedule.db";
|
private static string _filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data");
|
public static string DbFilePath
|
{
|
get => _filePath + "\\" + _dbName;
|
}
|
|
/// <summary>
|
/// 初始数据库
|
/// </summary>
|
/// <param name="backup"></param>
|
/// <param name="stringDefaultLength"></param>
|
/// <returns></returns>
|
public static bool InitTables(bool backup = false, int stringDefaultLength = 250)
|
{
|
var db = GetDb();
|
if (db == null)
|
return false;
|
|
Type[] types = new Type[] {
|
typeof(Entity.ScheduleCombine),
|
typeof(Entity.ScheduleCombineLog),
|
typeof(Entity.ScheduleAnaLog),
|
|
};
|
|
//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()
|
{
|
var filePath = DbFilePath;
|
if (!System.IO.File.Exists(filePath))
|
{
|
try
|
{
|
SQLiteConnection.CreateFile(filePath);
|
}
|
catch (Exception ex)
|
{
|
var errMsg = $".db 文件不存在!Path:{filePath}\r\n{ex.Message}";
|
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;
|
}
|
|
}
|
|
}
|