Files
2022-07-24 14:48:54 +08:00

281 lines
9.3 KiB
C#

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
{
/// <summary>
/// 数据库操作
/// </summary>
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("操作失败,出现异常请联系管理员!");
}
};
}
// ----- 插入
/// <summary>
/// 插入数据并返回主键
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="isCheck"></param>
/// <returns></returns>
public virtual ApiResult<int> InsertReturnId<T>(T t, bool isCheck = true) where T : class, new()
{
if (isCheck)
{
var resultValidate = t.Validate();
if (!resultValidate.IsSuccess) return ApiResult<int>.Failed(resultValidate.Msg);
}
int id = new SimpleClient<T>(Db).InsertReturnIdentity(t);
return ApiResult<int>.Success("", id);
}
/// <summary>
/// 批量插入
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="isCheck"></param>
/// <returns></returns>
public virtual ApiResult InsertRange<T>(List<T> 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();
}
// ----- 删除
/// <summary>
/// 根据主键删除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public virtual bool DeleteById<T>(dynamic id) where T : class, new()
{
return new SimpleClient<T>(Db).DeleteById(id);
}
/// <summary>
/// 批量删除
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public virtual bool DeleteRange<T>(List<int> ids) where T : class, new()
{
List<dynamic> ls = new List<dynamic>();
ids.ForEach(p => ls.Add(p));
return new SimpleClient<T>(Db).DeleteByIds(ls.ToArray());
}
// ----- 更新
/// <summary>
/// 更新
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="isCheck"></param>
/// <returns></returns>
public virtual ApiResult Update<T>(T t, bool isCheck = true) where T : class, new()
{
if (isCheck)
{
var resultValidate = t.Validate();
if (!resultValidate.IsSuccess) ApiResult.Failed(resultValidate.Msg);
}
new SimpleClient<T>(Db).Update(t);
return ApiResult.Success();
}
/// <summary>
/// 批量更新
/// </summary>
/// <param name="list"></param>
/// <param name="isCheck">是否数据校验</param>
/// <returns></returns>
public virtual ApiResult UpdateRange<T>(List<T> 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<T>(Db).UpdateRange(list.ToArray());
return ApiResult.Success();
}
// ----- 查询单条
/// <summary>
/// 根据主键获取实体
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public virtual T GetById<T>(dynamic id) where T : class, new()
{
return new SimpleClient<T>(Db).GetById(id);
}
/// <summary>
/// 根据条件获取实体,如果多条获取第一条
/// </summary>
/// <param name="whereExpression"></param>
/// <returns></returns>
public virtual T GetSingle<T>(Expression<Func<T, bool>> whereExpression) where T : class, new()
{
var simple = new SimpleClient<T>(Db);
try
{
return simple.GetSingle(whereExpression);
}
catch (InvalidOperationException)
{
return simple.GetList(whereExpression).FirstOrDefault();
}
catch (Exception ex)
{
string t = ex.Message;
throw;
}
}
// ----- 查询多条
/// <summary>
/// 获取所有
/// </summary>
/// <returns></returns>
public virtual List<T> GetList<T>() where T : class, new()
{
return new SimpleClient<T>(Db).GetList();
}
/// <summary>
/// 根据条件查询
/// </summary>
/// <param name="whereExpression">Lambd表达式</param>
/// <returns></returns>
public virtual List<T> GetList<T>(Expression<Func<T, bool>> whereExpression) where T : class, new()
{
return new SimpleClient<T>(Db).GetList(whereExpression);
}
/// <summary>
/// IN 查询
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public virtual List<T> GetIn<T>(List<int> ids) where T : class, new()
{
return Db.Queryable<T>().In(ids.ToArray()).ToList();
}
/// <summary>
/// 单表分页获取数据列表
/// </summary>
/// <param name="pageIndex">当前页</param>
/// <param name="pageSize">页大小</param>
/// <param name="whereExpression">Lambd表达式</param>
/// <param name="orderByExpression">排序字段,</param>
/// <param name="orderByType">排序方式</param>
/// <returns></returns>
public virtual PagerData<T> GetPageList<T>(int pageIndex, int pageSize, Expression<Func<T, bool>> whereExpression, Expression<Func<T, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc) where T : class, new()
{
if (pageIndex <= 1) pageIndex = 1;
if (pageSize <= 1) pageSize = 10;
PagerData<T> pagerData = new PagerData<T>();
PageModel page = new PageModel()
{
PageIndex = pageIndex,
PageSize = pageSize
};
if (whereExpression == null)
{
var exp = Expressionable.Create<T>();
whereExpression = exp.ToExpression();
}
List<T> ls = new SimpleClient<T>(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;
}
}
}