You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
1387 lines
54 KiB
1387 lines
54 KiB
using System.Data;
|
|
using System.Dynamic;
|
|
using System.Linq.Expressions;
|
|
using AgileObjects.AgileMapper;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Newtonsoft.Json.Linq;
|
|
using SqlSugar;
|
|
using Tiobon.Core.Common;
|
|
using Tiobon.Core.Common.Caches;
|
|
using Tiobon.Core.Common.DB.Dapper;
|
|
using Tiobon.Core.Common.DB.Dapper.Extensions;
|
|
using Tiobon.Core.Common.Enums;
|
|
using Tiobon.Core.Common.Extensions;
|
|
using Tiobon.Core.Common.Helper;
|
|
using Tiobon.Core.Common.UserManager;
|
|
using Tiobon.Core.DataAccess;
|
|
using Tiobon.Core.IRepository.Base;
|
|
using Tiobon.Core.IServices.BASE;
|
|
using Tiobon.Core.Model;
|
|
using Tiobon.Core.Model.Models;
|
|
using System.Reflection;
|
|
using System.Collections;
|
|
|
|
namespace Tiobon.Core.Services.BASE;
|
|
|
|
/// <summary>
|
|
/// 增删改查基础服务
|
|
/// </summary>
|
|
/// <typeparam name="TEntity"></typeparam>
|
|
/// <typeparam name="TEntityDto"></typeparam>
|
|
/// <typeparam name="TInsertDto"></typeparam>
|
|
/// <typeparam name="TEditDto"></typeparam>
|
|
public class BaseServices<TEntity, TEntityDto, TInsertDto, TEditDto> : IBaseServices<TEntity, TEntityDto, TInsertDto, TEditDto> where TEntity : class, new()
|
|
{
|
|
public ICaching _caching;
|
|
|
|
public BaseServices(IBaseRepository<TEntity> BaseDal = null, ICaching caching = null)
|
|
{
|
|
this.BaseDal = BaseDal;
|
|
_caching = caching;
|
|
}
|
|
|
|
//public IBaseRepository<TEntity> baseDal = new BaseRepository<TEntity>();
|
|
public IBaseRepository<TEntity> BaseDal { get; set; } //通过在子类的构造函数中注入,这里是基类,不用构造函数
|
|
|
|
public ISqlSugarClient Db => BaseDal.Db;
|
|
|
|
/// <summary>
|
|
/// 根据ID查询实体数据是否存在
|
|
/// </summary>
|
|
/// <param name="objId"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> AnyAsync(object objId)
|
|
{
|
|
var data = await BaseDal.AnyAsync(objId);
|
|
return data;
|
|
}
|
|
|
|
public async Task<bool> AnyAsync(Expression<Func<TEntity, bool>> whereExpression)
|
|
{
|
|
var data = await BaseDal.AnyAsync(whereExpression);
|
|
return data;
|
|
}
|
|
|
|
public virtual async Task<TEntityDto> QueryById(object objId)
|
|
{
|
|
var data = new TEntity();
|
|
var dto = Mapper.Map(data).ToANew<TEntityDto>();
|
|
|
|
Type entityType = typeof(TEntity);
|
|
string sql = @$"DECLARE @langId INT = 1,@ID BIGINT = '{objId}';
|
|
SELECT *,
|
|
isnull
|
|
((SELECT CASE WHEN @langId = 1 THEN UserName ELSE UserEname END
|
|
FROM Ghrs_User kk
|
|
WHERE kk.UserId = a.CreateBy),
|
|
'')
|
|
+ ' '
|
|
+ [dbo].[FLangKeyToValue] ('GHR_Common_000078', @langId, '于 ')
|
|
+ ' '
|
|
+ CONVERT (NVARCHAR (16), CreateTime, 121)
|
|
+ ' '
|
|
+ [dbo].[FLangKeyToValue] ('GHR_Common_000079', @langId, ' 创建')
|
|
CreateDataInfo,
|
|
isnull
|
|
((SELECT CASE WHEN @langId = 1 THEN UserName ELSE UserEname END
|
|
FROM Ghrs_User kk
|
|
WHERE kk.UserId = a.UpdateBy),
|
|
'')
|
|
+ ' '
|
|
+ [dbo].[FLangKeyToValue] ('GHR_Common_000078', @langId, '于')
|
|
+ ' '
|
|
+ CONVERT (NVARCHAR (16), UpdateTime, 121)
|
|
+ ' '
|
|
+ [dbo].[FLangKeyToValue]
|
|
('GHR_Common_000080', @langId, ' 最后修改')
|
|
UpdateDataInfo
|
|
FROM {entityType.GetEntityTableName()} a
|
|
WHERE a.Id = @ID AND IsEnable='1'";
|
|
dto = await Db.Ado.SqlQuerySingleAsync<TEntityDto>(sql);
|
|
return dto;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 根据ID查询一条数据
|
|
/// </summary>
|
|
/// <param name="objId">id(必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件</param>
|
|
/// <param name="blnUseCache">是否使用缓存</param>
|
|
/// <returns>数据实体</returns>
|
|
public async Task<TEntityDto> QueryById(object objId, bool blnUseCache = false)
|
|
{
|
|
var data = await BaseDal.QueryById(objId, blnUseCache);
|
|
return Mapper.Map(data).ToANew<TEntityDto>();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 根据ID查询数据
|
|
/// </summary>
|
|
/// <param name="lstIds">id列表(必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件</param>
|
|
/// <returns>数据实体列表</returns>
|
|
public async Task<List<TEntityDto>> QueryByIDs(object[] lstIds)
|
|
{
|
|
var data = await BaseDal.QueryByIDs(lstIds);
|
|
return Mapper.Map(data).ToANew<List<TEntityDto>>();
|
|
}
|
|
|
|
public virtual async Task<ServiceFormResult<TEntityDto>> QueryForm(QueryForm body)
|
|
{
|
|
var data = new ServiceFormResult<TEntityDto>();
|
|
string sql = string.Empty;
|
|
var dt = new DataTable();
|
|
|
|
if (body.id != null)
|
|
{
|
|
Type entityType = typeof(TEntity);
|
|
sql = @$"DECLARE @langId INT = '{body.langId}',@ID BIGINT = '{body.id}';
|
|
|
|
SELECT *,
|
|
isnull
|
|
((SELECT CASE WHEN @langId = 1 THEN UserName ELSE UserEname END
|
|
FROM Ghrs_User kk
|
|
WHERE kk.UserId = a.CreateBy),
|
|
'')
|
|
+ ' '
|
|
+ [dbo].[FLangKeyToValue] ('GHR_Common_000078', @langId, '于 ')
|
|
+ ' '
|
|
+ CONVERT (NVARCHAR (16), CreateTime, 121)
|
|
+ ' '
|
|
+ [dbo].[FLangKeyToValue] ('GHR_Common_000079', @langId, ' 创建')
|
|
CreateDataInfo,
|
|
isnull
|
|
((SELECT CASE WHEN @langId = 1 THEN UserName ELSE UserEname END
|
|
FROM Ghrs_User kk
|
|
WHERE kk.UserId = a.UpdateBy),
|
|
'')
|
|
+ ' '
|
|
+ [dbo].[FLangKeyToValue] ('GHR_Common_000078', @langId, '于')
|
|
+ ' '
|
|
+ CONVERT (NVARCHAR (16), UpdateTime, 121)
|
|
+ ' '
|
|
+ [dbo].[FLangKeyToValue]
|
|
('GHR_Common_000080', @langId, ' 最后修改')
|
|
UpdateDataInfo
|
|
FROM {entityType.GetEntityTableName()} a
|
|
WHERE a.Id = @ID";
|
|
data.result.DT_TableDataT1 = await Db.Ado.SqlQueryAsync<TEntityDto>(sql);
|
|
}
|
|
else
|
|
{
|
|
var list = new List<TEntity>
|
|
{
|
|
new TEntity()
|
|
};
|
|
|
|
data.result.DT_TableDataT1 = Mapper.Map(list).ToANew<List<TEntityDto>>();
|
|
|
|
}
|
|
#region JM_PageFormActionsT1
|
|
dynamic JM_PageFormActionsT1 = new ExpandoObject();
|
|
|
|
var toolbars = await _caching.GetAsync<List<FormToolbar>>(body.menuName + "FormToolbar");
|
|
if (toolbars == null || (toolbars != null && !toolbars.Any()))
|
|
{
|
|
sql = @$"SELECT field fnKey, [dbo].[FLangKeyToValue] (mkey, {body.langId}, label) fnTitle, icon
|
|
FROM Ghrs_PageSettingEdit
|
|
WHERE IsEnable = 1 AND pageNo = '{body.menuName}' AND elementType = 'FnKey'";
|
|
toolbars = await Db.Ado.SqlQueryAsync<FormToolbar>(sql);
|
|
if (toolbars.Any())
|
|
await _caching.SetAsync(body.menuName + "FormToolbar", toolbars);
|
|
}
|
|
|
|
|
|
JM_PageFormActionsT1.Toolbar = toolbars;
|
|
#endregion
|
|
|
|
#region JM_TableColumnT1
|
|
dynamic JM_TableColumnT1 = new ExpandoObject();
|
|
var tableColumn = new JArray();
|
|
sql = @$"SELECT field,
|
|
[dbo].[FLangKeyToValue] (mkey, {body.langId}, label)
|
|
label,
|
|
required,
|
|
editable,
|
|
rowNum,
|
|
colNum,
|
|
elementType,
|
|
dbo.FS_GetdataSourceBySet
|
|
(dataSource, APIDataSourceType, Ghrs_PageSettingEdit.APIDataSourceID)
|
|
dataSource,
|
|
defaultHidden,
|
|
isPrimaryKey,
|
|
isSingleColumn,multipleSelect
|
|
FROM Ghrs_PageSettingEdit
|
|
WHERE IsEnable = 1
|
|
AND pageNo = '{body.menuName}'
|
|
AND elementType NOT IN ('FnKey', 'PageGroup');";
|
|
dt = await Db.Ado.GetDataTableAsync(sql);
|
|
|
|
for (int i = 0; i < dt.Rows.Count; i++)
|
|
{
|
|
JObject item =
|
|
[
|
|
new JProperty("field", dt.Rows[i]["field"].ToString()),
|
|
new JProperty("label", dt.Rows[i]["label"].ToString()),
|
|
new JProperty("required",!string.IsNullOrWhiteSpace(dt.Rows[i]["required"].ToString())? Convert.ToBoolean(dt.Rows[i]["required"]):null),
|
|
new JProperty("editable",!string.IsNullOrWhiteSpace(dt.Rows[i]["editable"].ToString())? Convert.ToBoolean(dt.Rows[i]["editable"]):null),
|
|
new JProperty("rowNum",!string.IsNullOrWhiteSpace(dt.Rows[i]["rowNum"].ToString())? Convert.ToInt32(dt.Rows[i]["rowNum"]):null),
|
|
new JProperty("colNum",!string.IsNullOrWhiteSpace(dt.Rows[i]["colNum"].ToString())? Convert.ToInt32(dt.Rows[i]["colNum"]):null),
|
|
new JProperty("elementType", dt.Rows[i]["elementType"].ToString()),
|
|
new JProperty("dataSource", dt.Rows[i]["dataSource"].ToString()),
|
|
new JProperty("defaultHidden", dt.Rows[i]["defaultHidden"].ToString()),
|
|
new JProperty("isPrimaryKey", !string.IsNullOrWhiteSpace(dt.Rows[i]["isPrimaryKey"].ToString())? Convert.ToBoolean(dt.Rows[i]["isPrimaryKey"]):null),
|
|
new JProperty("isSingleColumn",!string.IsNullOrWhiteSpace(dt.Rows[i]["isSingleColumn"].ToString())? Convert.ToInt32(dt.Rows[i]["isSingleColumn"]):null),
|
|
new JProperty("multipleSelect",!string.IsNullOrWhiteSpace(dt.Rows[i]["multipleSelect"].ToString())? Convert.ToBoolean(dt.Rows[i]["multipleSelect"]):null),
|
|
];
|
|
tableColumn.Add(item);
|
|
}
|
|
JM_TableColumnT1.TableColumn = tableColumn;
|
|
#endregion
|
|
|
|
#region JM_PageFormT1
|
|
dynamic JM_PageFormT1 = new ExpandoObject();
|
|
var pageForm = new JArray();
|
|
JObject pageFormItem =
|
|
[
|
|
new JProperty("disabled", false),
|
|
new JProperty("labelAlign", "right"),
|
|
new JProperty("labelCol", "{span: 6}"),
|
|
new JProperty("labelWidth",120),
|
|
new JProperty("layout", "horizontal")
|
|
];
|
|
|
|
sql = $@"SELECT [dbo].[FLangKeyToValue] (MKey, {body.langId}, MenuName) pageTitle,
|
|
IUDProcedure apiName
|
|
FROM Ghrs_Menu
|
|
WHERE MenuNo = '{body.menuName}' AND IsEnable = 1";
|
|
dt = await Db.Ado.GetDataTableAsync(sql);
|
|
if (dt.Rows.Count > 0)
|
|
{
|
|
pageFormItem.Add(new JProperty("pageTitle", dt.Rows[0]["pageTitle"].ToString()));
|
|
pageFormItem.Add(new JProperty("apiName", dt.Rows[0]["apiName"].ToString()));
|
|
}
|
|
pageForm.Add(pageFormItem);
|
|
JM_PageFormT1.PageForm = pageForm;
|
|
#endregion
|
|
|
|
#region DT_PageMutiMsg
|
|
var DT_PageMutiMsg = await _caching.GetAsync<List<DT_PageMutiMsg>>("DT_PageMutiMsg");
|
|
if (DT_PageMutiMsg == null || (DT_PageMutiMsg != null && !DT_PageMutiMsg.Any()))
|
|
{
|
|
sql = $@"SELECT Langkey field,
|
|
CASE {body.langId}
|
|
WHEN 1 THEN isnull (Value01, LangValue)
|
|
WHEN 2 THEN isnull (Value02, LangValue)
|
|
WHEN 3 THEN isnull (Value03, LangValue)
|
|
WHEN 4 THEN isnull (Value04, LangValue)
|
|
WHEN 5 THEN isnull (Value05, LangValue)
|
|
WHEN 6 THEN isnull (Value06, LangValue)
|
|
WHEN 7 THEN isnull (Value07, LangValue)
|
|
WHEN 8 THEN isnull (Value08, LangValue)
|
|
WHEN 9 THEN isnull (Value09, LangValue)
|
|
WHEN 10 THEN isnull (Value10, LangValue)
|
|
END label
|
|
FROM Ghrs_LangKey
|
|
WHERE (LangKey LIKE 'GHR_Page%' OR LangKey LIKE 'GHR_Common%')
|
|
AND IsEnable = 1";
|
|
DT_PageMutiMsg = Db.Ado.SqlQuery<DT_PageMutiMsg>(sql);
|
|
if (DT_PageMutiMsg.Any())
|
|
await _caching.SetAsync("DT_PageMutiMsg", DT_PageMutiMsg);
|
|
}
|
|
#endregion
|
|
|
|
data.result.JM_PageFormActionsT1 = JM_PageFormActionsT1;
|
|
data.result.JM_TableColumnT1 = JM_TableColumnT1;
|
|
data.result.JM_PageFormT1 = JM_PageFormT1;
|
|
data.result.DT_PageMutiMsg = DT_PageMutiMsg;
|
|
return data;
|
|
}
|
|
|
|
#region 新增
|
|
|
|
/// <summary>
|
|
/// 写入实体数据
|
|
/// </summary>
|
|
/// <param name="entity">实体类</param>
|
|
/// <returns></returns>
|
|
public virtual async Task<long> Add(TInsertDto entity)
|
|
{
|
|
var entity1 = Mapper.Map(entity).ToANew<TEntity>();
|
|
if (UserContext.Context != null)
|
|
{
|
|
HttpRequest request = UserContext.Context.Request;
|
|
var api = request.Path.ObjToString().TrimEnd('/').ToLower();
|
|
var ip = GetUserIp(UserContext.Context);
|
|
|
|
BasePoco ent = entity1 as BasePoco;
|
|
|
|
ent.CreateIP = ip;
|
|
ent.CreateProg = api;
|
|
}
|
|
|
|
|
|
#region 检查是否存在相同值
|
|
CheckOnly(entity1);
|
|
#endregion
|
|
|
|
return await BaseDal.Add(entity1);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 批量插入实体(速度快)
|
|
/// </summary>
|
|
/// <param name="listEntity">实体集合</param>
|
|
/// <returns>影响行数</returns>
|
|
public virtual async Task<List<long>> Add(List<TInsertDto> listEntity)
|
|
{
|
|
if (listEntity != null && listEntity.Any())
|
|
{
|
|
var userId = App.User.ID;
|
|
var api = string.Empty;
|
|
var ip = string.Empty;
|
|
if (UserContext.Context != null)
|
|
{
|
|
HttpRequest request = UserContext.Context.Request;
|
|
api = request.Path.ObjToString().TrimEnd('/').ToLower();
|
|
ip = GetUserIp(UserContext.Context);
|
|
}
|
|
|
|
var list = Mapper.Map(listEntity).ToANew<List<TEntity>>();
|
|
list.ForEach(entity =>
|
|
{
|
|
BasePoco ent = entity as BasePoco;
|
|
ent.CreateIP = ip;
|
|
ent.CreateProg = api;
|
|
|
|
|
|
#region 检查是否存在相同值
|
|
CheckOnly(entity);
|
|
#endregion
|
|
});
|
|
return await BaseDal.Add(list);
|
|
}
|
|
else return default;
|
|
}
|
|
#endregion
|
|
|
|
/// <summary>
|
|
/// 更新实体数据
|
|
/// </summary>
|
|
/// <param name="entity">实体类</param>
|
|
/// <returns></returns>
|
|
public virtual async Task<bool> Update(long Id, TEditDto editModel)
|
|
{
|
|
HttpRequest request = UserContext.Context.Request;
|
|
var api = request.Path.ObjToString().TrimEnd('/').ToLower();
|
|
var ip = GetUserIp(UserContext.Context);
|
|
|
|
if (editModel == null || !await BaseDal.AnyAsync(Id))
|
|
return false;
|
|
|
|
var entity = await BaseDal.QueryById(Id);
|
|
ConvertTEditDto2TEntity(editModel, entity);
|
|
BasePoco ent = entity as BasePoco;
|
|
ent.UpdateIP = ip;
|
|
ent.UpdateProg = api;
|
|
CheckOnly(entity, Id);
|
|
return await BaseDal.Update(entity);
|
|
}
|
|
public async Task<bool> Update(Dictionary<long, TEditDto> editModels)
|
|
{
|
|
HttpRequest request = UserContext.Context.Request;
|
|
var api = request.Path.ObjToString().TrimEnd('/').ToLower();
|
|
var ip = GetUserIp(UserContext.Context);
|
|
|
|
List<TEntity> entities = new List<TEntity>();
|
|
foreach (var keyValuePairs in editModels)
|
|
{
|
|
if (keyValuePairs.Value == null || !BaseDal.Any(keyValuePairs.Key))
|
|
continue;
|
|
|
|
var entity = await BaseDal.QueryById(keyValuePairs.Key);
|
|
|
|
ConvertTEditDto2TEntity(keyValuePairs.Value, entity);
|
|
BasePoco ent = entity as BasePoco;
|
|
ent.UpdateIP = ip;
|
|
ent.UpdateProg = api;
|
|
CheckOnly(entity, keyValuePairs.Key);
|
|
entities.Add(entity);
|
|
}
|
|
|
|
return await BaseDal.Update(entities);
|
|
}
|
|
/// <summary>
|
|
/// 更新实体数据
|
|
/// </summary>
|
|
/// <param name="entity">实体类</param>
|
|
/// <returns></returns>
|
|
public async Task<bool> Update(List<TEntity> listEntity)
|
|
{
|
|
HttpRequest request = UserContext.Context.Request;
|
|
var api = request.Path.ObjToString().TrimEnd('/').ToLower();
|
|
var ip = GetUserIp(UserContext.Context);
|
|
listEntity.ForEach(entity =>
|
|
{
|
|
BasePoco ent = entity as BasePoco;
|
|
ent.UpdateIP = ip;
|
|
ent.UpdateProg = api;
|
|
});
|
|
return await BaseDal.Update(listEntity);
|
|
}
|
|
|
|
public async Task<bool> Update(TEntity entity, string where)
|
|
{
|
|
HttpRequest request = UserContext.Context.Request;
|
|
var api = request.Path.ObjToString().TrimEnd('/').ToLower();
|
|
var ip = GetUserIp(UserContext.Context);
|
|
BasePoco ent = entity as BasePoco;
|
|
ent.UpdateIP = ip;
|
|
ent.UpdateProg = api;
|
|
return await BaseDal.Update(entity, where);
|
|
}
|
|
|
|
public async Task<bool> Update(object operateAnonymousObjects)
|
|
{
|
|
return await BaseDal.Update(operateAnonymousObjects);
|
|
}
|
|
|
|
public async Task<bool> Update(TEntity entity, List<string> lstColumns = null, List<string> lstIgnoreColumns = null, string where = "")
|
|
{
|
|
return await BaseDal.Update(entity, lstColumns, lstIgnoreColumns, where);
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// 根据实体删除一条数据
|
|
/// </summary>
|
|
/// <param name="entity">实体类</param>
|
|
/// <returns></returns>
|
|
public async Task<bool> Delete(TEntity entity)
|
|
{
|
|
return await BaseDal.Delete(entity);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 删除指定ID的数据
|
|
/// </summary>
|
|
/// <param name="id">主键ID</param>
|
|
/// <returns></returns>
|
|
public async Task<bool> DeleteById(object id)
|
|
{
|
|
return await BaseDal.DeleteById(id);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 删除指定ID的数据
|
|
/// </summary>
|
|
/// <param name="id">主键ID</param>
|
|
/// <returns></returns>
|
|
public virtual async Task<bool> DeleteById1(object id)
|
|
{
|
|
var entity = await BaseDal.QueryById(id);
|
|
BasePoco ent = entity as BasePoco;
|
|
ent.IsEnable = 0;
|
|
return await BaseDal.Update(entity);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 删除指定ID集合的数据(批量删除)
|
|
/// </summary>
|
|
/// <param name="ids">主键ID集合</param>
|
|
/// <returns></returns>
|
|
public async Task<bool> DeleteByIds(object[] ids)
|
|
{
|
|
return await BaseDal.DeleteByIds(ids);
|
|
}
|
|
/// <summary>
|
|
/// 删除指定ID集合的数据(批量删除)
|
|
/// </summary>
|
|
/// <param name="ids">主键ID集合</param>
|
|
/// <returns></returns>
|
|
public virtual async Task<bool> DeleteByIds1(long[] ids)
|
|
{
|
|
HttpRequest request = UserContext.Context.Request;
|
|
var api = request.Path.ObjToString().TrimEnd('/').ToLower();
|
|
var ip = GetUserIp(UserContext.Context);
|
|
|
|
List<TEntity> entities = new List<TEntity>();
|
|
foreach (var id in ids)
|
|
{
|
|
if (id == null || !BaseDal.Any(id))
|
|
continue;
|
|
|
|
var entity = await BaseDal.QueryById(id);
|
|
|
|
BasePoco ent = entity as BasePoco;
|
|
ent.UpdateIP = ip;
|
|
ent.UpdateProg = api;
|
|
ent.IsEnable = 0;
|
|
entities.Add(entity);
|
|
}
|
|
|
|
return await BaseDal.Update(entities);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 根据表达式,删除实体
|
|
/// </summary>
|
|
/// <param name="whereExpression">表达式</param>
|
|
/// <returns></returns>
|
|
public async Task<bool> Delete(Expression<Func<TEntity, bool>> whereExpression)
|
|
{
|
|
return await BaseDal.Delete(whereExpression);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 查询所有数据
|
|
/// </summary>
|
|
/// <returns>数据列表</returns>
|
|
public async Task<List<TEntity>> Query()
|
|
{
|
|
return await BaseDal.Query();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 查询数据列表
|
|
/// </summary>
|
|
/// <param name="where">条件</param>
|
|
/// <returns>数据列表</returns>
|
|
public async Task<List<TEntity>> Query(string where)
|
|
{
|
|
return await BaseDal.Query(where);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 查询数据列表
|
|
/// </summary>
|
|
/// <param name="whereExpression">whereExpression</param>
|
|
/// <returns>数据列表</returns>
|
|
public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression)
|
|
{
|
|
return await BaseDal.Query(whereExpression);
|
|
}
|
|
|
|
public async Task<List<TEntityDto>> QueryDto(Expression<Func<TEntity, bool>> whereExpression)
|
|
{
|
|
var data = await BaseDal.Query(whereExpression);
|
|
return Mapper.Map(data).ToANew<List<TEntityDto>>();
|
|
}
|
|
public virtual async Task<TEntity> QuerySingle(object objId)
|
|
{
|
|
var entity = await BaseDal.QueryById(objId);
|
|
return entity;
|
|
}
|
|
public async Task<TEntity> QuerySingle(Expression<Func<TEntity, bool>> whereExpression)
|
|
{
|
|
var entitys = await BaseDal.Query(whereExpression);
|
|
var entity = entitys.FirstOrDefault();
|
|
if (entity == null)
|
|
return default;
|
|
else return entity;
|
|
}
|
|
public async Task<TEntityDto> QuerySingleDto(Expression<Func<TEntity, bool>> whereExpression)
|
|
{
|
|
var entity = await QuerySingle(whereExpression);
|
|
if (entity == null)
|
|
return default;
|
|
else return Mapper.Map(entity).ToANew<TEntityDto>();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 按照特定列查询数据列表
|
|
/// </summary>
|
|
/// <typeparam name="TResult"></typeparam>
|
|
/// <param name="expression"></param>
|
|
/// <returns></returns>
|
|
public async Task<List<TResult>> Query<TResult>(Expression<Func<TEntity, TResult>> expression)
|
|
{
|
|
return await BaseDal.Query(expression);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 按照特定列查询数据列表带条件排序
|
|
/// </summary>
|
|
/// <typeparam name="TResult"></typeparam>
|
|
/// <param name="whereExpression">过滤条件</param>
|
|
/// <param name="expression">查询实体条件</param>
|
|
/// <param name="orderByFileds">排序条件</param>
|
|
/// <returns></returns>
|
|
public async Task<List<TResult>> Query<TResult>(Expression<Func<TEntity, TResult>> expression, Expression<Func<TEntity, bool>> whereExpression, string orderByFileds)
|
|
{
|
|
return await BaseDal.Query(expression, whereExpression, orderByFileds);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 查询一个列表
|
|
/// </summary>
|
|
/// <param name="whereExpression">条件表达式</param>
|
|
/// <param name="strOrderByFileds">排序字段,如name asc,age desc</param>
|
|
/// <returns>数据列表</returns>
|
|
public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderByExpression, bool isAsc = true)
|
|
{
|
|
return await BaseDal.Query(whereExpression, orderByExpression, isAsc);
|
|
}
|
|
|
|
public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, string orderByFileds)
|
|
{
|
|
return await BaseDal.Query(whereExpression, orderByFileds);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 查询一个列表
|
|
/// </summary>
|
|
/// <param name="where">条件</param>
|
|
/// <param name="orderByFileds">排序字段,如name asc,age desc</param>
|
|
/// <returns>数据列表</returns>
|
|
public async Task<List<TEntity>> Query(string where, string orderByFileds)
|
|
{
|
|
return await BaseDal.Query(where, orderByFileds);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 根据sql语句查询
|
|
/// </summary>
|
|
/// <param name="sql">完整的sql语句</param>
|
|
/// <param name="parameters">参数</param>
|
|
/// <returns>泛型集合</returns>
|
|
public async Task<List<TEntity>> QuerySql(string sql, SugarParameter[] parameters = null)
|
|
{
|
|
return await BaseDal.QuerySql(sql, parameters);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 根据sql语句查询
|
|
/// </summary>
|
|
/// <param name="sql">完整的sql语句</param>
|
|
/// <param name="parameters">参数</param>
|
|
/// <returns>DataTable</returns>
|
|
public async Task<DataTable> QueryTable(string sql, SugarParameter[] parameters = null)
|
|
{
|
|
return await BaseDal.QueryTable(sql, parameters);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 查询前N条数据
|
|
/// </summary>
|
|
/// <param name="whereExpression">条件表达式</param>
|
|
/// <param name="top">前N条</param>
|
|
/// <param name="orderByFileds">排序字段,如name asc,age desc</param>
|
|
/// <returns>数据列表</returns>
|
|
public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, int top, string orderByFileds)
|
|
{
|
|
return await BaseDal.Query(whereExpression, top, orderByFileds);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 查询前N条数据
|
|
/// </summary>
|
|
/// <param name="where">条件</param>
|
|
/// <param name="top">前N条</param>
|
|
/// <param name="orderByFileds">排序字段,如name asc,age desc</param>
|
|
/// <returns>数据列表</returns>
|
|
public async Task<List<TEntity>> Query(string where, int top, string orderByFileds)
|
|
{
|
|
return await BaseDal.Query(where, top, orderByFileds);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 分页查询
|
|
/// </summary>
|
|
/// <param name="whereExpression">条件表达式</param>
|
|
/// <param name="pageIndex">页码(下标0)</param>
|
|
/// <param name="pageSize">页大小</param>
|
|
/// <param name="orderByFileds">排序字段,如name asc,age desc</param>
|
|
/// <returns>数据列表</returns>
|
|
public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, int pageIndex, int pageSize, string orderByFileds)
|
|
{
|
|
return await BaseDal.Query(whereExpression, pageIndex, pageSize, orderByFileds);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 分页查询
|
|
/// </summary>
|
|
/// <param name="where">条件</param>
|
|
/// <param name="pageIndex">页码(下标0)</param>
|
|
/// <param name="pageSize">页大小</param>
|
|
/// <param name="orderByFileds">排序字段,如name asc,age desc</param>
|
|
/// <returns>数据列表</returns>
|
|
public async Task<List<TEntity>> Query(string where, int pageIndex, int pageSize, string orderByFileds)
|
|
{
|
|
return await BaseDal.Query(where, pageIndex, pageSize, orderByFileds);
|
|
}
|
|
|
|
public async Task<PageModel<TEntity>> QueryPage(Expression<Func<TEntity, bool>> whereExpression, int pageIndex = 1, int pageSize = 20, string orderByFileds = null)
|
|
{
|
|
return await BaseDal.QueryPage(whereExpression, pageIndex, pageSize, orderByFileds);
|
|
}
|
|
|
|
public virtual async Task<ServicePageResult<TEntityDto>> QueryFilterPage(QueryBody filter)
|
|
{
|
|
return await QueryFilterPage(filter, null);
|
|
}
|
|
public virtual async Task<ServicePageResult<TEntityDto>> QueryFilterPage(QueryBody filter, string condition, bool? IsEnable = true)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(filter.orderBy))
|
|
filter.orderBy = "CreateTime1 DESC";
|
|
|
|
if (filter.pageSize == 0)
|
|
filter.pageSize = 10000;
|
|
|
|
Type entityType = typeof(TEntity);
|
|
|
|
var countSql = @$" SELECT COUNT(1) FROM {entityType.GetEntityTableName()}";
|
|
var sql1 = @$"DECLARE @langId INT = {filter.langId};";
|
|
var sql = @$" SELECT *,
|
|
ISNULL ((SELECT CASE WHEN @langId = 1 THEN UserName ELSE UserEname END
|
|
FROM Ghrs_User B
|
|
WHERE B.UserId = A.CreateBy),
|
|
'') CreateDataInfo,
|
|
ISNULL ((SELECT CASE WHEN @langId = 1 THEN UserName ELSE UserEname END
|
|
FROM Ghrs_User B
|
|
WHERE B.UserId = A.UpdateBy),
|
|
'') UpdateDataInfo, ISNULL(A.UpdateTime, A.CreateTime) CreateTime1
|
|
FROM {entityType.GetEntityTableName()} A";
|
|
|
|
string conditions = " WHERE 1=1 ";
|
|
|
|
if (IsEnable == true)
|
|
conditions += " AND IsEnable = 1";
|
|
else if (IsEnable == false)
|
|
conditions += " AND IsEnable = 0";
|
|
|
|
if (!string.IsNullOrWhiteSpace(condition))
|
|
conditions += " AND " + condition;
|
|
|
|
var properties = entityType.GetGenericProperties();
|
|
|
|
if (filter.jsonParam != null)
|
|
foreach (JProperty jProperty in filter.jsonParam.Properties())
|
|
{
|
|
var name = jProperty.Name;
|
|
var value = jProperty.Value.ToString();
|
|
if (name == "page" || name == "pageSize" || !properties.Any(x => x.Name == name))
|
|
continue;
|
|
if (!string.IsNullOrWhiteSpace(value))
|
|
{
|
|
var jsonParam = JsonHelper.JsonToObj<JsonParam>(value);
|
|
|
|
switch (jsonParam.operationKey)
|
|
{
|
|
case "Include":
|
|
conditions += $" AND {name} LIKE '%{jsonParam.columnValue}%'";
|
|
break;
|
|
case "NotInclude":
|
|
conditions += $" AND {name} NOT LIKE '%{jsonParam.columnValue}%'";
|
|
break;
|
|
case "IsNull":
|
|
conditions += $" AND {name} IS NULL";
|
|
break;
|
|
case "NotNull":
|
|
conditions += $" AND {name} IS NOT NULL";
|
|
break;
|
|
case "Equal":
|
|
conditions += $" AND {name} ='{jsonParam.columnValue}'";
|
|
break;
|
|
case "NotEqual":
|
|
conditions += $" AND {name} !='{jsonParam.columnValue}'";
|
|
break;
|
|
case "GreaterOrEqual"://大于等于
|
|
conditions += $" AND {name} >='{jsonParam.columnValue}'";
|
|
break;
|
|
case "Greater"://大于
|
|
conditions += $" AND {name} >'{jsonParam.columnValue}'";
|
|
break;
|
|
case "LessOrEqual"://小于等于
|
|
conditions += $" AND {name} <='{jsonParam.columnValue}'";
|
|
break;
|
|
case "Less"://小于
|
|
conditions += $" AND {name} <'{jsonParam.columnValue}'";
|
|
break;
|
|
case "EqualAny"://
|
|
if (jsonParam.columnValue != null)
|
|
{
|
|
var ids = JsonHelper.JsonToObj<List<string>>(jsonParam.columnValue.ToString());
|
|
|
|
conditions += $" AND {name} IN ({string.Join(",", ids.Select(id => "'" + id + "'"))})";
|
|
}
|
|
break;
|
|
case "NotEqualAny"://
|
|
if (jsonParam.columnValue != null)
|
|
{
|
|
var ids = JsonHelper.JsonToObj<List<string>>(jsonParam.columnValue.ToString());
|
|
|
|
conditions += $" AND {name} NOT IN ({string.Join(",", ids.Select(id => "'" + id + "'"))})";
|
|
}
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
sql += conditions;
|
|
countSql += conditions;
|
|
int total = await Db.Ado.GetIntAsync(countSql);
|
|
|
|
sql = "SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY " + filter.orderBy + ") NUM FROM (SELECT * FROM (" + sql + " ";
|
|
sql += ") A ) B ) C";
|
|
|
|
sql += " WHERE NUM <= " + filter.pageNum * filter.pageSize + " AND NUM >" + (filter.pageNum - 1) * filter.pageSize;
|
|
sql = sql1 + sql;
|
|
var entitys = await Db.Ado.SqlQueryAsync<TEntityDto>(sql);
|
|
|
|
return new ServicePageResult<TEntityDto>(filter.pageNum, total, filter.pageSize, entitys);
|
|
|
|
}
|
|
public async Task<ServiceResult<string>> ExportExcel(QueryExport body)
|
|
{
|
|
QueryBody filter = new QueryBody();
|
|
filter.pageNum = 1;
|
|
filter.pageSize = 1000000;
|
|
filter.langId = body.langId;
|
|
|
|
var condition = "1=1";
|
|
if (body.exportSet.SelectRowKeys != null && body.exportSet.SelectRowKeys.Any())
|
|
condition += $" AND Id IN({string.Join(",", body.exportSet.SelectRowKeys)})";
|
|
|
|
var data = await QueryFilterPage(filter, condition);
|
|
|
|
|
|
string sql = $@"SELECT *
|
|
FROM Ghrs_PageSettingQuery
|
|
WHERE IsEnable = 1
|
|
AND PageNo = '{body.menuName}'
|
|
AND (defaultHidden = 'false' OR defaultHidden is null)
|
|
ORDER BY SortNo ASC";
|
|
|
|
var columns = await Db.Ado.SqlQueryAsync<QueryExportColumn>(sql);
|
|
|
|
var fieldDescs = new Dictionary<string, string>();
|
|
if (body.exportSet.ExFields.Any())
|
|
body.exportSet.ExFields.ForEach(x =>
|
|
{
|
|
if (columns.Any(o => o.field == x))
|
|
fieldDescs.Add(x, columns.FirstOrDefault(o => o.field == x)?.label);
|
|
|
|
|
|
});
|
|
else
|
|
fieldDescs = columns.ToDictionary(item => item.field, item => item.label);
|
|
var dt = ToDataTable(data.result.DT_TableDataT1, fieldDescs, null);
|
|
// 获取所有列名
|
|
var dtColumns = dt.Columns;
|
|
|
|
var id = SnowFlakeSingle.instance.getID();
|
|
var physicsPath = $"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot";
|
|
var path = $"{$"{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}export{Path.DirectorySeparatorChar}{id}{Path.DirectorySeparatorChar}"}";
|
|
if (!Directory.Exists(physicsPath + path))
|
|
Directory.CreateDirectory(physicsPath + path);
|
|
|
|
path = path + body.exportSet.TitleName + ".xlsx";
|
|
NPOIHelper.ExportExcel(dt, null, "sheet1", physicsPath + path);
|
|
return ServiceResult<string>.OprateSuccess("导出成功", path);
|
|
}
|
|
/// <summary>
|
|
/// 列名按照前端显示顺序导出
|
|
/// </summary>
|
|
/// <param name="columns"></param>
|
|
/// <param name="ExportFields"></param>
|
|
/// <returns></returns>
|
|
public static (List<string>, List<string>) Sort(Dictionary<string, string> columns, List<string> ExportFields)
|
|
{
|
|
List<string> fields = new List<string>();
|
|
List<string> colunms = new List<string>();
|
|
if (ExportFields == null || ExportFields.Count == 0)
|
|
{
|
|
return (columns.Keys.ToList(), columns.Values.ToList());
|
|
}
|
|
|
|
foreach (var field in ExportFields)
|
|
{
|
|
foreach (var item in columns)
|
|
{
|
|
if (item.Key == field)
|
|
{
|
|
fields.Add(item.Key);
|
|
colunms.Add(item.Value);
|
|
}
|
|
}
|
|
}
|
|
|
|
return (fields, colunms);
|
|
}
|
|
public static DataTable ToDataTable(List<TEntityDto> list, Dictionary<string, string> fieldDescs = null, params string[] propertyName)
|
|
{
|
|
var (fields, colunms) = Sort(fieldDescs, null);
|
|
|
|
List<string> propertyNameList = new List<string>();
|
|
if (propertyName != null)
|
|
{
|
|
propertyNameList.AddRange(propertyName);
|
|
}
|
|
DataTable result = new DataTable();
|
|
if (list.Count > 0)
|
|
{
|
|
PropertyInfo[] propertys = list[0].GetType().GetProperties();
|
|
for (int i = 0; i < fields.Count; i++)
|
|
{
|
|
foreach (PropertyInfo pi in propertys)
|
|
{
|
|
if (propertyNameList.Count == 0)
|
|
{
|
|
//if (DBNull.Value.Equals(pi.PropertyType))
|
|
//{
|
|
// // pi.PropertyType = DateTime;
|
|
//}
|
|
Type colType = pi.PropertyType;
|
|
if (colType.IsGenericType && colType.GetGenericTypeDefinition() == typeof(Nullable<>))
|
|
{
|
|
colType = colType.GetGenericArguments()[0];
|
|
}
|
|
if (fields[i] == pi.Name)
|
|
{
|
|
result.Columns.Add(colunms[i], colType);
|
|
}
|
|
//result.Columns.Add(pi.Name, pi.PropertyType);
|
|
}
|
|
else
|
|
{
|
|
if (propertyNameList.Contains(pi.Name))
|
|
{
|
|
if (fields[i] == pi.Name)
|
|
result.Columns.Add(fields[i], pi.PropertyType);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
for (int i = 0; i < list.Count; i++)
|
|
{
|
|
ArrayList tempList = new ArrayList();
|
|
for (int j = 0; j < fields.Count; j++)
|
|
{
|
|
foreach (PropertyInfo pi in propertys)
|
|
{
|
|
if (fields[j] == pi.Name)
|
|
{
|
|
if (propertyNameList.Count == 0)
|
|
{
|
|
object obj = pi.GetValue(list[i], null);
|
|
tempList.Add(obj);
|
|
}
|
|
else
|
|
{
|
|
if (propertyNameList.Contains(pi.Name))
|
|
{
|
|
object obj = pi.GetValue(list[i], null);
|
|
tempList.Add(obj);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
object[] array = tempList.ToArray();
|
|
result.LoadDataRow(array, true);
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
public async virtual Task<ServiceResult<ExcelData>> ImportExcel(IFormFile file)
|
|
{
|
|
//long id = SnowFlakeSingle.instance.getID();
|
|
//var physicsPath = $"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot";
|
|
//var path = $"{$"{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}import{Path.DirectorySeparatorChar}{id}{Path.DirectorySeparatorChar}"}";
|
|
//if (!Directory.Exists(physicsPath + path))
|
|
// Directory.CreateDirectory(physicsPath + path);
|
|
|
|
|
|
return ServiceResult<ExcelData>.OprateSuccess("导入成功!");
|
|
}
|
|
public virtual async Task<ServiceResult<string>> DownloadExcel(string menuName)
|
|
{
|
|
|
|
var tableNmae = string.Empty;
|
|
Type entityType = typeof(TEntity);
|
|
|
|
|
|
var sql = $@"SELECT Row_Number ()
|
|
OVER (ORDER BY CONVERT (INT, rowNum), CONVERT (INT, colNum))
|
|
sortNum,
|
|
field,
|
|
[dbo].[FLangKeyToValue] (mkey, 1, label)
|
|
label,
|
|
dbo.FS_GetdataSourceBySet
|
|
(dataSource, APIDataSourceType, Ghrs_PageSettingEdit.APIDataSourceID)
|
|
dataSource,
|
|
required,
|
|
dataType,
|
|
CONVERT (NVARCHAR (1000), '')
|
|
commentText -- StaffWith
|
|
,
|
|
elementType
|
|
+ CASE WHEN multipleSelect = 'true' THEN '_multiple' ELSE '' END
|
|
elementType -- 增加多选判断
|
|
FROM Ghrs_PageSettingEdit
|
|
WHERE IsEnable = 1
|
|
AND elementType NOT IN ('FnKey', 'PageGroup')
|
|
AND pageNo = '{menuName}'
|
|
--and editable = 'true'
|
|
AND defaultHidden ! = 'true'
|
|
AND elementType ! = 'FileUpload'
|
|
AND dataType ! = ''";
|
|
|
|
var columns = await Db.Ado.SqlQueryAsync<QueryExportColumn>(sql);
|
|
|
|
var dt = await Db.Ado.GetDataTableAsync("SELECT * FROM " + entityType.GetEntityTableName() + " WHERE IsEnable=1");
|
|
|
|
//columns = columns.WhereIF(param.exportSet.ExFields.Any(), x => param.exportSet.ExFields.Contains(x.field)).ToList();
|
|
|
|
await ReportHelper.ImportTemplate(Db, columns, dt, menuName);
|
|
|
|
|
|
//var physicsPath = $"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot";
|
|
//var path = $"{$"{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}ExcelTemplate{Path.DirectorySeparatorChar}"}";
|
|
//if (!Directory.Exists(physicsPath + path))
|
|
// Directory.CreateDirectory(physicsPath + path);
|
|
|
|
//Type entityType = typeof(TEntity);
|
|
//var fileName = entityType.GetEntityTableName() + ".xlsx";
|
|
//var result = ServiceResult<string>.OprateSuccess(fileName, physicsPath + path + fileName);
|
|
var result = ServiceResult<string>.OprateSuccess(null, null);
|
|
return result;
|
|
}
|
|
|
|
public async Task<List<TResult>> QueryMuch<T, T2, T3, TResult>(Expression<Func<T, T2, T3, object[]>> joinExpression, Expression<Func<T, T2, T3, TResult>> selectExpression, Expression<Func<T, T2, T3, bool>> whereLambda = null) where T : class, new()
|
|
{
|
|
return await BaseDal.QueryMuch(joinExpression, selectExpression, whereLambda);
|
|
}
|
|
|
|
public async Task<PageModel<TEntity>> QueryPage(PaginationModel pagination)
|
|
{
|
|
var express = DynamicLinqFactory.CreateLambda<TEntity>(pagination.Conditions);
|
|
return await QueryPage(express, pagination.PageIndex, pagination.PageSize, pagination.OrderByFileds);
|
|
}
|
|
|
|
#region 分表
|
|
|
|
public async Task<List<long>> AddSplit(TEntity entity)
|
|
{
|
|
return await BaseDal.AddSplit(entity);
|
|
}
|
|
|
|
public async Task<bool> UpdateSplit(TEntity entity, DateTime dateTime)
|
|
{
|
|
return await BaseDal.UpdateSplit(entity, dateTime);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 根据实体删除一条数据
|
|
/// </summary>
|
|
/// <param name="entity">实体类</param>
|
|
/// <returns></returns>
|
|
public async Task<bool> DeleteSplit(TEntity entity, DateTime dateTime)
|
|
{
|
|
return await BaseDal.DeleteSplit(entity, dateTime);
|
|
}
|
|
|
|
public async Task<TEntity> QueryByIdSplit(object objId)
|
|
{
|
|
return await BaseDal.QueryByIdSplit(objId);
|
|
}
|
|
|
|
public async Task<PageModel<TEntity>> QueryPageSplit(Expression<Func<TEntity, bool>> whereExpression, DateTime beginTime, DateTime endTime, int pageIndex = 1, int pageSize = 20, string orderByFields = null)
|
|
{
|
|
return await BaseDal.QueryPageSplit(whereExpression, beginTime, endTime, pageIndex, pageSize, orderByFields);
|
|
}
|
|
|
|
#endregion
|
|
|
|
public static string GetUserIp(HttpContext context)
|
|
{
|
|
string realIP = null;
|
|
string forwarded = null;
|
|
string remoteIpAddress = context.Connection.RemoteIpAddress.ToString();
|
|
if (context.Request.Headers.ContainsKey("X-Real-IP"))
|
|
{
|
|
realIP = context.Request.Headers["X-Real-IP"].ToString();
|
|
if (realIP != remoteIpAddress)
|
|
{
|
|
remoteIpAddress = realIP;
|
|
}
|
|
}
|
|
if (context.Request.Headers.ContainsKey("X-Forwarded-For"))
|
|
{
|
|
forwarded = context.Request.Headers["X-Forwarded-For"].ToString();
|
|
if (forwarded != remoteIpAddress)
|
|
{
|
|
remoteIpAddress = forwarded;
|
|
}
|
|
}
|
|
remoteIpAddress = remoteIpAddress.Replace("::ffff:", null);
|
|
return remoteIpAddress;
|
|
}
|
|
|
|
|
|
#region 辅助方法
|
|
/// <summary>
|
|
/// 转换TEditDto2TEntity
|
|
/// </summary>
|
|
/// <param name="pTargetObjSrc"></param>
|
|
/// <param name="pTargetObjDest"></param>
|
|
/// <returns></returns>
|
|
protected void ConvertTEditDto2TEntity(TEditDto source, TEntity dest)
|
|
{
|
|
foreach (System.Reflection.PropertyInfo mItem in typeof(TEditDto).GetProperties())
|
|
{
|
|
if (dest.HasField(mItem.Name))
|
|
dest.SetValueForField(mItem.Name, mItem.GetValue(source, null));
|
|
}
|
|
//dest.SetValueForField(DbConsts.ColunmName_LastModificationTime, DateTimeHelper.Now());
|
|
//if (_currentUserId != default)
|
|
//{
|
|
// //dest.SetValueForField(DbConsts.ColunmName_LastModifierId, _currentUserId);
|
|
// dest.SetValueForField(DbConsts.ColunmName_LastModifier, _currentUserName);
|
|
//}
|
|
|
|
//if (_currentTenantId != null)
|
|
//{
|
|
// dest.SetValueForField(DbConsts.ColunmName_TenantId, _currentTenantId);
|
|
//}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 获取根据ID查询的条件
|
|
/// </summary>
|
|
/// <param name="id"></param>
|
|
/// <returns></returns>
|
|
protected QueryFilter QueryFilterById(Guid id)
|
|
{
|
|
return new QueryFilter
|
|
{
|
|
PageIndex = 1,
|
|
PageSize = 1,
|
|
Sorting = string.Empty,
|
|
Conditions = string.Empty
|
|
};
|
|
}
|
|
|
|
#region 检查表中是否已经存在相同代码的数据
|
|
|
|
public static void CheckOnly(TEntity entity, long? id = null)
|
|
{
|
|
Type entityType = typeof(TEntity);
|
|
var tableName = entityType.GetEntityTableName();
|
|
|
|
var names = new List<string>();
|
|
var values = new List<object>();
|
|
var descriptions = new List<string>();
|
|
entity.GetOnlyList(out names, out values, out descriptions);
|
|
for (int i = 0; i < names.Count; i++)
|
|
{
|
|
CheckCodeExist(tableName, names[i], values[i], id != null ? ModifyType.Edit : ModifyType.Add, descriptions[i], id);
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// 检查表中是否已经存在相同代码的数据
|
|
/// </summary>
|
|
/// <param name="tableName">表名</param>
|
|
/// <param name="fieldName">字段名</param>
|
|
/// <param name="fieldValue">字段值</param>
|
|
/// <param name="modifyType">ModifyType.Add,ModifyType.Edit</param>
|
|
/// <param name="rowid">ModifyType.Edit时修改记录的ROW_ID值</param>
|
|
/// <param name="promptName">判断栏位的提示名称</param>
|
|
public static void CheckCodeExist(string tableName, string fieldName, object fieldValue, ModifyType modifyType, string promptName, long? rowid = null)
|
|
{
|
|
try
|
|
{
|
|
CheckCodeExist(tableName, fieldName, fieldValue, modifyType, rowid, promptName, null);
|
|
}
|
|
catch (Exception)
|
|
{
|
|
throw;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 检查表中是否已经存在相同代码的数据
|
|
/// </summary>
|
|
/// <param name="tableName">表名</param>
|
|
/// <param name="fieldName">字段名</param>
|
|
/// <param name="fieldValue">字段值</param>
|
|
/// <param name="whereCondition">条件</param>
|
|
/// <param name="modifyType">ModifyType.Add,ModifyType.Edit</param>
|
|
/// <param name="rowid">ModifyType.Edit时修改记录的ROW_ID值</param>
|
|
/// <param name="promptName">判断栏位的提示名称</param>
|
|
/// <param name="whereCondition">Where后的条件,如:IS_ALCON='Y'</param>
|
|
public static bool CheckCodeExist(string tableName, string fieldName, object fieldValue, ModifyType modifyType, long? rowid, string promptName, string whereCondition)
|
|
{
|
|
try
|
|
{
|
|
bool result = false;
|
|
if (modifyType == ModifyType.Add)
|
|
{
|
|
string sql = string.Empty;
|
|
sql = "SELECT COUNT(*) FROM " + tableName + " WHERE " + fieldName + "='" + fieldValue + "' AND IsEnable=1";
|
|
|
|
if (!string.IsNullOrEmpty(whereCondition))
|
|
sql += " AND " + whereCondition;
|
|
|
|
int count = Convert.ToInt32(DbAccess.ExecuteScalar(sql));
|
|
if (count > 0)
|
|
{
|
|
result = true;
|
|
throw new Exception(string.Format("{0}【{1}】已经存在!", promptName, fieldValue));
|
|
}
|
|
else
|
|
result = false;
|
|
|
|
}
|
|
else if (modifyType == ModifyType.Edit)
|
|
{
|
|
string sql = string.Empty;
|
|
sql = "SELECT COUNT(*) FROM " + tableName + " WHERE " + fieldName + "='" + fieldValue + "' AND IsEnable=1 AND ID!='" + rowid.Value + "'";
|
|
|
|
if (!string.IsNullOrEmpty(whereCondition))
|
|
sql += " AND " + whereCondition;
|
|
|
|
int count = Convert.ToInt32(DbAccess.ExecuteScalar(sql));
|
|
if (count > 0)
|
|
{
|
|
result = true;
|
|
throw new Exception(string.Format("{0}【{1}】已经存在!", promptName, fieldValue));
|
|
}
|
|
else
|
|
result = false;
|
|
}
|
|
return result;
|
|
}
|
|
catch (Exception)
|
|
{
|
|
throw;
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region 自动编号
|
|
/// <summary>
|
|
/// 自动编号
|
|
/// </summary>
|
|
/// <param name="tableCode">表名</param>
|
|
/// <param name="columnCode">栏位名</param>
|
|
/// <param name="prefixTemp">前缀</param>
|
|
/// <returns></returns>
|
|
public async Task<string> GenerateContinuousSequence(string tableCode, string columnCode, string prefixTemp)
|
|
{
|
|
try
|
|
{
|
|
string result = string.Empty;
|
|
int length = 7;
|
|
int tempLength = 6;
|
|
int sequence;
|
|
|
|
#region 查询
|
|
DbSelect dbSelect = new DbSelect(tableCode + " A", "A", null);
|
|
dbSelect.IsInitDefaultValue = false;
|
|
|
|
if (!string.IsNullOrEmpty(prefixTemp))
|
|
dbSelect.Select("MAX(SUBSTRING(A." + columnCode + "," + (prefixTemp.Length + 1).ToString() + "," + tempLength.ToString() + "))");
|
|
else
|
|
dbSelect.Select("MAX(A." + columnCode + ")");
|
|
//}
|
|
//dbSelect.Select("MAX(CONVERT(DECIMAL,SUBSTRING(A.ISSUE_NO," + (prefix.Length + dateString.Length + 1).ToString() + "," + tempLength.ToString() + ")))");
|
|
if (!string.IsNullOrEmpty(prefixTemp))
|
|
dbSelect.Where("SUBSTRING(A." + columnCode + ",1," + (prefixTemp.Length).ToString() + ")", " = ", prefixTemp);
|
|
dbSelect.Where("LEN(A." + columnCode + ")", "=", length);
|
|
string sql = dbSelect.GetSql();
|
|
//await Db.Ado.GetScalarAsync(sql)
|
|
string maxSequence = Convert.ToString(await Db.Ado.GetScalarAsync(sql));
|
|
#endregion
|
|
//tempLength = tempLength - dateString.Length;
|
|
if (string.IsNullOrEmpty(maxSequence))
|
|
result = prefixTemp + Convert.ToString(1).PadLeft(tempLength, '0');
|
|
else
|
|
{
|
|
if (!string.IsNullOrEmpty(prefixTemp))
|
|
{
|
|
if (int.TryParse(maxSequence, out sequence))
|
|
{
|
|
sequence += 1;
|
|
if (sequence.ToString().Length > tempLength)
|
|
throw new Exception("自动生成字串长度已经超过设定长度!");
|
|
}
|
|
else
|
|
throw new Exception("表中的数据无法进行自动编号,请联系软件开发商!");
|
|
result = prefixTemp + sequence.ToString().PadLeft(tempLength, '0');
|
|
}
|
|
else
|
|
{
|
|
if (int.TryParse(maxSequence, out sequence))
|
|
{
|
|
sequence += 1;
|
|
if (sequence.ToString().Length > length)
|
|
throw new Exception("自动生成字串长度已经超过设定长度!");
|
|
}
|
|
else
|
|
throw new Exception("表中的数据无法进行自动编号,请联系软件开发商!");
|
|
result = sequence.ToString().PadLeft(length, '0');
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
catch (Exception) { throw; }
|
|
}
|
|
#endregion
|
|
|
|
#region 获取通用参数设定
|
|
public async Task<string> GetParaLabel(string key, string value)
|
|
{
|
|
string label = value;
|
|
var list = await _caching.GetAsync<List<Ghrs_ParaDetail>>(key);
|
|
if (list == null || (list != null && !list.Any()))
|
|
{
|
|
string sql = $"SELECT * FROM Ghrs_ParaDetail WHERE ParaMasterNo ='{key}' ORDER BY SortNo ASC";
|
|
list = DbAccess.QueryList<Ghrs_ParaDetail>(sql);
|
|
if (list.Any())
|
|
await _caching.SetAsync(key, list);
|
|
}
|
|
|
|
if (list.Any(x => x.ParaDetailNo == value))
|
|
label = list.FirstOrDefault(x => x.ParaDetailNo == value)?.ParaDetailName;
|
|
return label;
|
|
}
|
|
#endregion
|
|
|
|
public string GetQueryString(string sqlSelect, int? currentPage = null, int? pageSize = null, string sortField = null, string sortDirection = null)
|
|
{
|
|
string queryString = string.Empty;
|
|
if (string.IsNullOrEmpty(sortField))
|
|
queryString = "SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY ROW_ID) NUM FROM (SELECT * FROM (" + sqlSelect + " WHERE 1=1 ";
|
|
else
|
|
{
|
|
if (!string.IsNullOrEmpty(sortDirection))
|
|
queryString = "SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY " + sortField + " " + sortDirection + ") NUM FROM (SELECT * FROM (" + sqlSelect + " ";
|
|
else
|
|
queryString = "SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY " + sortField + " DESC) NUM FROM (SELECT * FROM (" + sqlSelect + " ";
|
|
}
|
|
queryString += ") A ) B ) C";
|
|
if (currentPage != null && pageSize != null)
|
|
queryString += " WHERE NUM <= " + currentPage * pageSize + " AND NUM >" + (currentPage - 1) * pageSize;
|
|
return queryString;
|
|
}
|
|
|
|
//public int GetTotalCount(string sqlSelect)
|
|
//{
|
|
// string sql = string.Empty;
|
|
|
|
// try
|
|
// {
|
|
// int count = Convert.ToInt32(DBHelper.ExecuteScalar(sql));
|
|
// return count;
|
|
// }
|
|
// catch (Exception Ex)
|
|
// {
|
|
// throw;
|
|
// }
|
|
//}
|
|
|
|
#endregion
|
|
} |