using SqlSugar;
using System.Data;
using System.Linq.Expressions;
using Yi.Framework.Common.Models;
using Yi.Framework.Model.Models;
using Yi.Framework.Model.Query;
/***这里面写的代码不会给覆盖,如果要重新生成请删除 Repository.cs ***/
namespace Yi.Framework.Repository
{
///
/// 仓储模式
///
///
public class Repository : DataContext, IRepository where T : BaseModelEntity,new()
{
public ISqlSugarClient _Db { get; set; }
///
/// 构造函数
///
///
public Repository(ISqlSugarClient context) : base(context)//注意这里要有默认值等于null
{
_Db = context;
}
///
/// 添加返回实体
///
///
///
public async Task InsertReturnEntityAsync(T entity)
{
entity.Id =SnowFlakeSingle.instance.getID();
return await Db.Insertable(entity).ExecuteReturnEntityAsync();
}
///
/// 更新忽略空值
///
///
///
public async Task UpdateIgnoreNullAsync(T entity)
{
return await Db.Updateable(entity).IgnoreColumns(true).ExecuteCommandAsync()>0;
}
///
/// 逻辑多删除
///
///
public async Task DeleteByLogicAsync(List ids)
{
var entitys = await Db.Queryable().Where(u => ids.Contains(u.Id)).ToListAsync();
entitys.ForEach(u=>u.IsDeleted=true);
return await Db.Updateable(entitys).ExecuteCommandAsync()>0;
}
///
/// 调用存储过程
///
///
///
///
///
public async Task> StoreAsync(string storeName, object para)
{
return await Db.Ado.UseStoredProcedure().SqlQueryAsync(storeName, para);
}
///
/// 多条件查询
///
///
///
public async Task> GetListAsync(QueryCondition pars)
{
return await QueryConditionHandler(pars).ToListAsync();
}
///
/// 仓储扩展方法:单表查询通用分页
///
///
public async Task>> CommonPageAsync(QueryPageCondition pars)
{
RefAsync tolCount = 0;
var result = await QueryConditionHandler(new QueryCondition() {OrderBys=pars.OrderBys,Parameters=pars.Parameters } ).ToPageListAsync(pars.Index, pars.Size, tolCount);
return new PageModel>
{
Total = tolCount.Value,
Data = result
};
}
private ISugarQueryable QueryConditionHandler(QueryCondition pars)
{
var sugarParamters = pars.Parameters.Select(it => (IConditionalModel)new ConditionalModel()
{
ConditionalType = it.Type,
FieldName = it.Key,
FieldValue = it.Value
}).ToList();
var query = Db.Queryable();
if (pars.OrderBys != null)
{
foreach (var item in pars.OrderBys)
{
query.OrderBy(item.ToSqlFilter());
}
}
return query.Where(sugarParamters);
}
}
}