2023-07-05 10:20:08 +08:00
|
|
|
using System;
|
|
|
|
using System.Linq;
|
2023-07-03 02:34:01 +08:00
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
|
|
|
|
namespace BITKit;
|
|
|
|
|
2023-07-05 10:20:08 +08:00
|
|
|
public interface IDatabaseContext<T> where T : class
|
|
|
|
{
|
|
|
|
void Add(T entity);
|
|
|
|
void Remove(T entity);
|
|
|
|
T[] GetArray();
|
|
|
|
bool TrySearch(Func<T, bool> searchFactory, out T result);
|
|
|
|
bool TrySearchArray(Func<T, bool> searchFactory, out T[] result);
|
|
|
|
}
|
|
|
|
|
|
|
|
public class SqlLiteContext<T> : DbContext,IDatabaseContext<T> where T : class
|
2023-07-03 02:34:01 +08:00
|
|
|
{
|
2023-07-06 16:32:57 +08:00
|
|
|
|
2023-07-03 02:34:01 +08:00
|
|
|
public DbSet<T> context { get; private set; }
|
|
|
|
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
|
|
|
{
|
2023-07-06 16:32:57 +08:00
|
|
|
var sql = SQLiteContextHelper.GetConnectionString<T>();
|
2023-07-03 02:34:01 +08:00
|
|
|
optionsBuilder.UseSqlite(sql);
|
|
|
|
}
|
2023-07-05 10:20:08 +08:00
|
|
|
public virtual void Add(T entity)
|
|
|
|
{
|
|
|
|
context.Add(entity);
|
|
|
|
SaveChanges();
|
|
|
|
}
|
|
|
|
public virtual void Remove(T entity)
|
|
|
|
{
|
|
|
|
context.Remove(entity);
|
|
|
|
SaveChanges();
|
|
|
|
}
|
|
|
|
public virtual T[] GetArray()
|
|
|
|
{
|
|
|
|
return context.ToArray();
|
|
|
|
}
|
|
|
|
public virtual bool TrySearch(Func<T,bool> searchFactory,out T result)
|
|
|
|
{
|
|
|
|
result = context.FirstOrDefault(searchFactory);
|
|
|
|
return result != null;
|
|
|
|
}
|
|
|
|
/// <summary>
|
|
|
|
/// 搜索数组
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="searchFactory"></param>
|
|
|
|
/// <param name="result"></param>
|
|
|
|
/// <returns></returns>
|
|
|
|
public virtual bool TrySearchArray(Func<T, bool> searchFactory, out T[] result)
|
|
|
|
{
|
|
|
|
result = context.Where(searchFactory).ToArray();
|
|
|
|
return result.Length > 0;
|
|
|
|
}
|
2023-07-06 16:32:57 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
public static class SQLiteContextHelper
|
|
|
|
{
|
|
|
|
private const string _database = "Database";
|
|
|
|
|
|
|
|
public static string GetConnectionString(string key)
|
|
|
|
{
|
|
|
|
GetConnectionSqlAndPath(key,out var connectionSql,out var path);
|
|
|
|
BIT4Log.Log($"已创建数据库链接:{path}");
|
|
|
|
return connectionSql;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static string GetConnectionString<T>()
|
|
|
|
{
|
|
|
|
GetConnectionSqlAndPath(typeof(T).Name,out var connectionSql,out var path);
|
|
|
|
BIT4Log.Log<T>($"已创建数据库链接:{path}");
|
|
|
|
return connectionSql;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static void GetConnectionSqlAndPath(string name,out string connectionSql,out string path)
|
|
|
|
{
|
|
|
|
PathHelper.GetFolderPath(_database);
|
|
|
|
path = PathHelper.GetPath(_database, $"{name}.db");
|
|
|
|
connectionSql = $"Data Source={path}";
|
|
|
|
}
|
|
|
|
}
|