using Appointment.Entity;
using Appointment.Entity.Utility;
using Appointment.Entity.ValidateAttribute;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace Appointment.Repository
{
///
/// 数据库操作
///
public class DbContext
{
static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(DbContext));
public SqlSugarClient Db;
public DbContext()
{
string conn = BaseConfig.App(new string[] { "ConnectionString" });
if (string.IsNullOrWhiteSpace(conn)) throw new Exception("未获取到数据库连接信息");
Db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = conn,
DbType = DbType.SqlServer,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true,
});
Db.Aop.OnError = (exp) =>
{
if (!string.IsNullOrWhiteSpace(exp.Sql))
{
string spar = string.Empty;
if (exp.Parametres != null)
{
SugarParameter[] parss = (SugarParameter[])exp.Parametres;
if (parss.Length > 0)
{
foreach (SugarParameter item in parss)
{
spar += $"{item.ParameterName}={item.Value.ToString()},";
}
}
}
log.Error($"sql语句:{exp.Sql} 参数:{spar}");
log.Error($"错误信息:{exp.Message}");
throw new Exception("操作失败,出现异常请联系管理员!");
}
};
}
// ----- 插入
///
/// 插入数据并返回主键
///
///
///
///
///
public virtual ApiResult InsertReturnId(T t, bool isCheck = true) where T : class, new()
{
if (isCheck)
{
var resultValidate = t.Validate();
if (!resultValidate.IsSuccess) return ApiResult.Failed(resultValidate.Msg);
}
int id = new SimpleClient(Db).InsertReturnIdentity(t);
return ApiResult.Success("", id);
}
///
/// 批量插入
///
///
///
///
///
public virtual ApiResult InsertRange(List list, bool isCheck = true) where T : class, new()
{
if (list == null || list.Count <= 0) return ApiResult.Success("没有可提交的数据");
if (isCheck)
{
var resultValidate = ApiResult.Success();
for (int i = 0; i < list.Count; i++)
{
resultValidate = list[i].Validate();
if (!resultValidate.IsSuccess) return ApiResult.Failed(resultValidate.Msg);
}
}
int rows = Db.Insertable(list.ToArray()).ExecuteCommand();
return ApiResult.Success();
}
// ----- 删除
///
/// 根据主键删除
///
///
///
public virtual bool DeleteById(dynamic id) where T : class, new()
{
return new SimpleClient(Db).DeleteById(id);
}
///
/// 批量删除
///
///
///
public virtual bool DeleteRange(List ids) where T : class, new()
{
List ls = new List();
ids.ForEach(p => ls.Add(p));
return new SimpleClient(Db).DeleteByIds(ls.ToArray());
}
// ----- 更新
///
/// 更新
///
///
///
///
///
public virtual ApiResult Update(T t, bool isCheck = true) where T : class, new()
{
if (isCheck)
{
var resultValidate = t.Validate();
if (!resultValidate.IsSuccess) ApiResult.Failed(resultValidate.Msg);
}
new SimpleClient(Db).Update(t);
return ApiResult.Success();
}
///
/// 批量更新
///
///
/// 是否数据校验
///
public virtual ApiResult UpdateRange(List list, bool isCheck = true) where T : class, new()
{
if (list == null || list.Count <= 0) return ApiResult.Success("没有可修改的数据");
if (isCheck)
{
var resultValidate = ApiResult.Success();
for (int i = 0; i < list.Count; i++)
{
resultValidate = list[i].Validate();
if (!resultValidate.IsSuccess) return ApiResult.Failed(resultValidate.Msg);
}
}
new SimpleClient(Db).UpdateRange(list.ToArray());
return ApiResult.Success();
}
// ----- 查询单条
///
/// 根据主键获取实体
///
///
///
public virtual T GetById(dynamic id) where T : class, new()
{
return new SimpleClient(Db).GetById(id);
}
///
/// 根据条件获取实体,如果多条获取第一条
///
///
///
public virtual T GetSingle(Expression> whereExpression) where T : class, new()
{
var simple = new SimpleClient(Db);
try
{
return simple.GetSingle(whereExpression);
}
catch (InvalidOperationException)
{
return simple.GetList(whereExpression).FirstOrDefault();
}
catch (Exception ex)
{
string t = ex.Message;
throw;
}
}
// ----- 查询多条
///
/// 获取所有
///
///
public virtual List GetList() where T : class, new()
{
return new SimpleClient(Db).GetList();
}
///
/// 根据条件查询
///
/// Lambd表达式
///
public virtual List GetList(Expression> whereExpression) where T : class, new()
{
return new SimpleClient(Db).GetList(whereExpression);
}
///
/// IN 查询
///
///
///
public virtual List GetIn(List ids) where T : class, new()
{
return Db.Queryable().In(ids.ToArray()).ToList();
}
///
/// 单表分页获取数据列表
///
/// 当前页
/// 页大小
/// Lambd表达式
/// 排序字段,
/// 排序方式
///
public virtual PagerData GetPageList(int pageIndex, int pageSize, Expression> whereExpression, Expression> orderByExpression = null, OrderByType orderByType = OrderByType.Asc) where T : class, new()
{
if (pageIndex <= 1) pageIndex = 1;
if (pageSize <= 1) pageSize = 10;
PagerData pagerData = new PagerData();
PageModel page = new PageModel()
{
PageIndex = pageIndex,
PageSize = pageSize
};
if (whereExpression == null)
{
var exp = Expressionable.Create();
whereExpression = exp.ToExpression();
}
List ls = new SimpleClient(Db).GetPageList(whereExpression, page, orderByExpression, orderByType);
if (ls != null && ls.Count > 0)
{
pagerData.Data = ls;
}
else
{
pagerData.Data = null;
}
pagerData.PageIndex = page.PageIndex;
pagerData.PageSize = page.PageSize;
pagerData.Total = page.PageCount;
return pagerData;
}
}
}