Merge branch 'Test.IRC' of http://192.168.3.69:2000/XCKJ/irc-netcore-api into Test.IRC

IRC_NewDev
he 2023-10-13 13:39:13 +08:00
commit b62a1e5d88
28 changed files with 204 additions and 811 deletions

View File

@ -228,7 +228,6 @@ namespace IRaCIS.Core.API.Controllers
} }
[HttpPost, Route("Study/PreArchiveStudy")] [HttpPost, Route("Study/PreArchiveStudy")]
[TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })] [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
public async Task<IResponseOutput> PreArchiveStudy(PreArchiveStudyCommand preArchiveStudyCommand, public async Task<IResponseOutput> PreArchiveStudy(PreArchiveStudyCommand preArchiveStudyCommand,
@ -264,12 +263,6 @@ namespace IRaCIS.Core.API.Controllers
} }
//public string UploadOOSTest(string filePath, string route)
//{
//}
/// <summary>Dicom 归档</summary> /// <summary>Dicom 归档</summary>
[HttpPost, Route("Study/ArchiveStudy")] [HttpPost, Route("Study/ArchiveStudy")]
[DisableFormValueModelBinding] [DisableFormValueModelBinding]
@ -443,260 +436,43 @@ namespace IRaCIS.Core.API.Controllers
} }
public class UploadNoneDicomFileCommand
/// <summary>
/// 上传临床数据 多文件
/// </summary>
/// <param name="subjectVisitId"></param>
/// <returns></returns>
[HttpPost("ClinicalData/UploadVisitClinicalData/{trialId:guid}/{subjectVisitId:guid}")]
[DisableRequestSizeLimit]
//[Authorize(Policy = IRaCISPolicy.CRC)]
[TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
public async Task<IResponseOutput> UploadVisitClinicalData(Guid subjectVisitId)
{ {
await _qCCommon.VerifyIsCRCSubmmitAsync(_repository, _userInfo, subjectVisitId); public Guid TrialId { get; set; }
var sv = _repository.Where<SubjectVisit>(t => t.Id == subjectVisitId).Select(t => new { t.TrialId, t.SiteId, t.SubjectId }).FirstOrDefault().IfNullThrowException(); public Guid SubjectVisitId { get; set; }
public Guid NoneDicomStudyId { get; set; }
public Guid StudyMonitorId { get; set; }
await FileUploadAsync(async (fileName) =>
public List<OSSFileDTO> UploadedFileList { get; set; } = new List<OSSFileDTO>();
public class OSSFileDTO
{ {
var (serverFilePath, relativePath, fileRealName) = FileStoreHelper.GetClinicalDataPath(_hostEnvironment, fileName, sv.TrialId, sv.SiteId, sv.SubjectId, subjectVisitId); public string FilePath { get; set; }
//插入临床pdf 路径 public string FileName { get; set; }
await _repository.AddAsync(new PreviousPDF() public int FileFize { get; set; }
{
SubjectVisitId = subjectVisitId,
IsVisist = true,
DataType = ClinicalDataType.MedicalHistory,
UploadType = ClinicalUploadType.PDF,
SubjectId = sv.SubjectId,
TrialId = sv.TrialId,
ClinicalLevel = ClinicalLevel.Subject,
Path = relativePath,
FileName = fileRealName
});
return serverFilePath;
});
await _repository.SaveChangesAsync();
return ResponseOutput.Ok();
} }
/// <summary>
/// 上传临床数据模板
/// </summary>
/// <param name="trialId"></param>
/// <returns></returns>
[HttpPost("ClinicalData/UploadClinicalTemplate")]
[DisableRequestSizeLimit]
[TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "BeforeOngoingCantOpt", "AfterStopCannNotOpt" })]
public async Task<IResponseOutput<List<FileDto>>> UploadClinicalTemplate(Guid? trialId)
{
if (trialId == null)
trialId = default(Guid);
var filerelativePath = string.Empty;
List<FileDto> fileDtos = new List<FileDto>();
await FileUploadAsync(async (fileName) =>
{
var (serverFilePath, relativePath, fileRealName) = FileStoreHelper.GetClinicalTemplatePath(_hostEnvironment, fileName, trialId.Value);
//插入临床pdf 路径
filerelativePath = relativePath;
fileDtos.Add(new FileDto()
{
FileName = fileName,
Path = relativePath
});
await Task.CompletedTask;
return serverFilePath;
});
return ResponseOutput.Ok(fileDtos);
} }
/// <summary>
/// 上传阅片临床数据
/// </summary>
/// <param name="trialId"></param>
/// <param name="subjectId"></param>
/// <param name="readingId"></param>
/// <returns></returns>
[HttpPost("ClinicalData/UploadClinicalData/{trialId:guid}/{subjectId:guid}/{readingId:guid}")]
[DisableRequestSizeLimit]
[TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
public async Task<IResponseOutput<List<FileDto>>> UploadReadClinicalData(Guid trialId, Guid subjectId, Guid readingId)
{
var filerelativePath = string.Empty;
List<FileDto> fileDtos = new List<FileDto>();
var siteid = await _repository.Where<Subject>(x => x.Id == subjectId).Select(x => x.SiteId).FirstOrDefaultAsync();
await FileUploadAsync(async (fileName) =>
{
var (serverFilePath, relativePath, fileRealName) = FileStoreHelper.GetReadClinicalDataPath(_hostEnvironment, fileName, trialId, siteid, subjectId, readingId);
//插入临床pdf 路径
filerelativePath = relativePath;
fileDtos.Add(new FileDto()
{
FileName = fileName,
Path = relativePath
});
await Task.CompletedTask;
return serverFilePath;
});
return ResponseOutput.Ok(fileDtos);
}
/// <summary>
/// 上传截图
/// </summary>
/// <param name="subjectId"></param>
/// <returns></returns>
[HttpPost("Printscreen/UploadPrintscreen/{subjectId:guid}")]
[TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
public async Task<IResponseOutput<FileDto>> UploadPrintscreen(Guid subjectId)
{
var subjectInfo = await this._repository.Where<Subject>(x => x.Id == subjectId).FirstNotNullAsync();
FileDto fileDto = new FileDto();
await FileUploadAsync(async (fileName) =>
{
var (serverFilePath, relativePath, fileRealName) = FileStoreHelper.GetUploadPrintscreenFilePath(_hostEnvironment, fileName, subjectInfo.TrialId, subjectInfo.SiteId, subjectInfo.Id);
fileDto.Path = relativePath;
fileDto.FileName = fileName;
await Task.CompletedTask;
return serverFilePath;
});
return ResponseOutput.Ok(fileDto);
}
/// <summary>
/// 上传Reading问题的图像
/// </summary>
/// <param name="trialId"></param>
/// <param name="visitTaskId"></param>
/// <returns></returns>
[HttpPost("VisitTask/UploadReadingAnswerImage/{trialId:guid}/{visitTaskId:guid}")]
[TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
public async Task<IResponseOutput<FileDto>> UploadReadingAnswerImage(Guid trialId, Guid visitTaskId)
{
FileDto fileDto = new FileDto();
await FileUploadAsync(async (fileName) =>
{
var (serverFilePath, relativePath, fileRealName) = FileStoreHelper.GetFilePath(_hostEnvironment, fileName, trialId, visitTaskId, StaticData.Folder.JudgeTask);
fileDto.Path = relativePath;
fileDto.FileName = fileName;
await Task.CompletedTask;
return serverFilePath;
});
return ResponseOutput.Ok(fileDto);
}
/// <summary>
/// 上传裁判任务的图像
/// </summary>
/// <param name="trialId"></param>
/// <param name="visitTaskId"></param>
/// <returns></returns>
[HttpPost("VisitTask/UploadJudgeTaskImage/{trialId:guid}/{visitTaskId:guid}")]
[TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
public async Task<IResponseOutput<FileDto>> UploadJudgeTaskImage(Guid trialId, Guid visitTaskId)
{
FileDto fileDto = new FileDto();
await FileUploadAsync(async (fileName) =>
{
var (serverFilePath, relativePath, fileRealName) = FileStoreHelper.GetFilePath(_hostEnvironment, fileName, trialId, visitTaskId, StaticData.Folder.JudgeTask);
fileDto.Path = relativePath;
fileDto.FileName = fileName;
await Task.CompletedTask;
return serverFilePath;
});
return ResponseOutput.Ok(fileDto);
}
/// <summary>
/// 上传医学审核图片
/// </summary>
/// <param name="trialId"></param>
/// <param name="taskMedicalReviewId"></param>
/// <returns></returns>
[HttpPost("TaskMedicalReview/UploadMedicalReviewImage/{trialId:guid}/{taskMedicalReviewId:guid}")]
[TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
public async Task<IResponseOutput<FileDto>> UploadMedicalReviewImage(Guid trialId, Guid taskMedicalReviewId)
{
string path = string.Empty;
FileDto fileDto = new FileDto();
await FileUploadAsync(async (fileName) =>
{
var (serverFilePath, relativePath, fileRealName) = FileStoreHelper.GetMedicalReviewImage(_hostEnvironment, fileName, trialId, taskMedicalReviewId);
//await _repository.UpdatePartialFromQueryAsync<TaskMedicalReview>(x => x.Id == taskMedicalReviewId, x => new TaskMedicalReview()
//{
// ImagePath = relativePath,
// FileName = fileName,
//});
path = relativePath;
fileDto.Path = relativePath;
fileDto.FileName = fileName;
return serverFilePath;
});
await _repository.SaveChangesAsync();
return ResponseOutput.Ok(fileDto);
}
/// <summary> /// <summary>
/// 上传非Dicom 文件 支持压缩包 多文件上传 /// 上传非Dicom 文件 支持压缩包 多文件上传
/// </summary> /// </summary>
/// <param name="formCollection"></param>
/// <param name="subjectVisitId"></param>
/// <param name="noneDicomStudyId"></param>
/// <param name="studyMonitorId"></param>
/// <param name="_noneDicomStudyRepository"></param> /// <param name="_noneDicomStudyRepository"></param>
/// <returns></returns> /// <returns></returns>
//[DisableRequestSizeLimit] //[DisableRequestSizeLimit]
[RequestSizeLimit(1_073_741_824)] [HttpPost("NoneDicomStudy/UploadNoneDicomFile")]
[HttpPost("NoneDicomStudy/UploadNoneDicomFile/{trialId:guid}/{subjectVisitId:guid}/{noneDicomStudyId:guid}/{studyMonitorId:guid}")]
[TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })] [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
//[Authorize(Policy = IRaCISPolicy.CRC)] //[Authorize(Policy = IRaCISPolicy.CRC)]
public async Task<IResponseOutput> UploadNoneDicomFile(IFormCollection formCollection, Guid subjectVisitId, Guid noneDicomStudyId, Guid studyMonitorId, public async Task<IResponseOutput> UploadNoneDicomFile(UploadNoneDicomFileCommand incommand,
[FromServices] IRepository<NoneDicomStudy> _noneDicomStudyRepository, [FromServices] IRepository<StudyMonitor> _studyMonitorRepository) [FromServices] IRepository<NoneDicomStudy> _noneDicomStudyRepository, [FromServices] IRepository<StudyMonitor> _studyMonitorRepository)
{ {
var subjectVisitId = incommand.SubjectVisitId;
var studyMonitorId = incommand.StudyMonitorId;
var noneDicomStudyId = incommand.NoneDicomStudyId;
await _qCCommon.VerifyIsCRCSubmmitAsync(_repository, _userInfo, subjectVisitId); await _qCCommon.VerifyIsCRCSubmmitAsync(_repository, _userInfo, subjectVisitId);
var sv = (await _repository.Where<SubjectVisit>(t => t.Id == subjectVisitId).Select(t => new { t.TrialId, t.SiteId, t.SubjectId }).FirstOrDefaultAsync()).IfNullThrowConvertException(); var sv = (await _repository.Where<SubjectVisit>(t => t.Id == subjectVisitId).Select(t => new { t.TrialId, t.SiteId, t.SubjectId }).FirstOrDefaultAsync()).IfNullThrowConvertException();
@ -705,28 +481,19 @@ namespace IRaCIS.Core.API.Controllers
studyMonitor.UploadFinishedTime = DateTime.Now; studyMonitor.UploadFinishedTime = DateTime.Now;
await FileUploadAsync(async (fileName) => foreach (var item in incommand.UploadedFileList)
{ {
await _repository.AddAsync(new NoneDicomStudyFile() { FileName = item.FileName, Path = item.FilePath, NoneDicomStudyId = noneDicomStudyId });
var (serverFilePath, relativePath, fileRealName) = FileStoreHelper.GetNoneDicomFilePath(_hostEnvironment, fileName, sv.TrialId, sv.SiteId, sv.SubjectId, subjectVisitId); }
await _repository.AddAsync(new NoneDicomStudyFile() { FileName = fileRealName, Path = relativePath, NoneDicomStudyId = noneDicomStudyId });
return serverFilePath;
});
var uploadFinishedTime = DateTime.Now; var uploadFinishedTime = DateTime.Now;
//// 上传非Dicom 后 将状态改为待提交 分为普通上传 和QC后重传 普通上传时才改为待提交
//await _repository.UpdatePartialFromQueryAsync<SubjectVisit>(t => t.Id == subjectVisitId && t.SubmitState == SubmitStateEnum.None, u => new SubjectVisit() { SubmitState = SubmitStateEnum.ToSubmit });
var noneDicomStudy = await _noneDicomStudyRepository.FirstOrDefaultAsync((t => t.Id == noneDicomStudyId)); var noneDicomStudy = await _noneDicomStudyRepository.FirstOrDefaultAsync((t => t.Id == noneDicomStudyId));
noneDicomStudy.FileCount = noneDicomStudy.FileCount + formCollection.Files.Count; noneDicomStudy.FileCount = noneDicomStudy.FileCount + incommand.UploadedFileList.Count;
studyMonitor.FileCount = formCollection.Files.Count; studyMonitor.FileCount = incommand.UploadedFileList.Count;
studyMonitor.FileSize = formCollection.Files.Sum(t => t.Length); studyMonitor.FileSize = incommand.UploadedFileList.Sum(t => t.FileFize);
studyMonitor.IsDicom = false; studyMonitor.IsDicom = false;
studyMonitor.IsDicomReUpload = false; studyMonitor.IsDicomReUpload = false;
studyMonitor.StudyId = noneDicomStudyId; studyMonitor.StudyId = noneDicomStudyId;
@ -742,6 +509,7 @@ namespace IRaCIS.Core.API.Controllers
/// <summary> /// <summary>
/// 一致性核查 excel上传 支持三种格式 /// 一致性核查 excel上传 支持三种格式
/// </summary> /// </summary>
@ -982,9 +750,6 @@ namespace IRaCIS.Core.API.Controllers
} }
/// <summary> /// <summary>
/// 上传文件( 不是医生个人的文件)[FileUpload] /// 上传文件( 不是医生个人的文件)[FileUpload]
/// 例如:阅片章程等 /// 例如:阅片章程等
@ -1057,8 +822,6 @@ namespace IRaCIS.Core.API.Controllers
} }
[HttpPost, Route("enroll/downloadResume/{trialId:guid}/{language}")] [HttpPost, Route("enroll/downloadResume/{trialId:guid}/{language}")]
[TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })] [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
[AllowAnonymous] [AllowAnonymous]
@ -1068,6 +831,7 @@ namespace IRaCIS.Core.API.Controllers
return ResponseOutput.Ok(zipPath); return ResponseOutput.Ok(zipPath);
} }
} }
#endregion #endregion
@ -1084,8 +848,6 @@ namespace IRaCIS.Core.API.Controllers
private readonly IWebHostEnvironment _hostEnvironment; private readonly IWebHostEnvironment _hostEnvironment;
public UploadDownLoadController(IMapper mapper, IUserInfo userInfo, IMediator mediator, IWebHostEnvironment hostEnvironment) public UploadDownLoadController(IMapper mapper, IUserInfo userInfo, IMediator mediator, IWebHostEnvironment hostEnvironment)
{ {
_hostEnvironment = hostEnvironment; _hostEnvironment = hostEnvironment;
@ -1094,104 +856,6 @@ namespace IRaCIS.Core.API.Controllers
_userInfo = userInfo; _userInfo = userInfo;
} }
/// <summary> 缩略图 </summary>
[AllowAnonymous]
[HttpGet("Common/LocalFilePreview")]
public async Task<FileContentResult> LocalFilePreview(string relativePath)
{
var _fileStorePath = FileStoreHelper.GetPhysicalFilePath(_hostEnvironment, relativePath);
var storePreviewPath = _fileStorePath + ".preview.jpeg";
if (!System.IO.File.Exists(storePreviewPath))
{
ImageHelper.ResizeSave(_fileStorePath, storePreviewPath);
}
return new FileContentResult(await System.IO.File.ReadAllBytesAsync(storePreviewPath), "image/jpeg");
}
/// <summary> 通用文件下载 </summary>
[AllowAnonymous]
[HttpGet("CommonDocument/DownloadCommonDoc")]
public async Task<IActionResult> DownloadCommonFile(string code, [FromServices] IRepository<CommonDocument> _commonDocumentRepository)
{
var (filePath, fileName) = await FileStoreHelper.GetCommonDocPhysicalFilePathAsync(_hostEnvironment, _commonDocumentRepository, code);
new FileExtensionContentTypeProvider().Mappings.TryGetValue(Path.GetExtension(filePath), out var contentType);
return File(System.IO.File.OpenRead(filePath), contentType ?? "application/octet-stream", fileName);
}
/// <summary>
/// 下载项目临床数据文件
/// </summary>
/// <param name="clinicalDataTrialSetId"></param>
/// <param name="_clinicalDataTrialSetRepository"></param>
/// <returns></returns>
[AllowAnonymous]
[HttpGet("CommonDocument/DownloadTrialClinicalFile")]
public async Task<IActionResult> DownloadTrialClinicalFile(Guid clinicalDataTrialSetId, [FromServices] IRepository<ClinicalDataTrialSet> _clinicalDataTrialSetRepository)
{
var (filePath, fileName) = await FileStoreHelper.GetTrialClinicalPathAsync(_hostEnvironment, _clinicalDataTrialSetRepository, clinicalDataTrialSetId);
new FileExtensionContentTypeProvider().Mappings.TryGetValue(Path.GetExtension(filePath), out var contentType);
return File(System.IO.File.OpenRead(filePath), contentType ?? "application/octet-stream", fileName);
}
/// <summary>
/// 下载系统临床数据文件
/// </summary>
/// <param name="clinicalDataSystemSetId"></param>
/// <param name="_clinicalDataSystemSetRepository"></param>
/// <returns></returns>
[AllowAnonymous]
[HttpGet("CommonDocument/DownloadSystemClinicalFile")]
public async Task<IActionResult> DownloadSystemClinicalFile(Guid clinicalDataSystemSetId, [FromServices] IRepository<ClinicalDataSystemSet> _clinicalDataSystemSetRepository)
{
var (filePath, fileName) = await FileStoreHelper.GetSystemClinicalPathAsync(_hostEnvironment, _clinicalDataSystemSetRepository, clinicalDataSystemSetId);
new FileExtensionContentTypeProvider().Mappings.TryGetValue(Path.GetExtension(filePath), out var contentType);
return File(System.IO.File.OpenRead(filePath), contentType ?? "application/octet-stream", fileName);
}
/// <summary>
///上传项目签名文档
/// </summary>
/// <param name="trialId"></param>
/// <returns></returns>
[HttpPost("TrialDocument/UploadTrialDoc/{trialId:guid}")]
[DisableRequestSizeLimit]
[DisableFormValueModelBinding]
public async Task<IResponseOutput> UploadTrialDoc(Guid trialId)
{
return await SingleFileUploadAsync((fileName) => FileStoreHelper.GetTrialSignDocPath(_hostEnvironment, trialId, fileName));
}
/// <summary>
/// 上传系统签名文档
/// </summary>
/// <returns></returns>
[HttpPost("TrialDocument/UploadSystemDoc")]
[DisableRequestSizeLimit]
[DisableFormValueModelBinding]
public async Task<IResponseOutput> UploadSysTemDoc()
{
return await SingleFileUploadAsync((fileName) => FileStoreHelper.GetSystemSignDocPath(_hostEnvironment, fileName));
}
/// <summary> /// <summary>
@ -1208,19 +872,6 @@ namespace IRaCIS.Core.API.Controllers
} }
/// <summary>
/// 上传系统通知文档
/// </summary>
/// <returns></returns>
[HttpPost("SystemNotice/UploadSystemNoticeDoc")]
[DisableRequestSizeLimit]
[DisableFormValueModelBinding]
public async Task<IResponseOutput> UploadSystemNoticeDoc()
{
return await SingleFileUploadAsync((fileName) => FileStoreHelper.GetSystemNoticePath(_hostEnvironment, fileName));
}
public enum UploadFileType public enum UploadFileType
{ {

View File

@ -159,7 +159,7 @@
<Folder Include="Properties\PublishProfiles\" /> <Folder Include="Properties\PublishProfiles\" />
</ItemGroup> </ItemGroup>
<ProjectExtensions><VisualStudio><UserProperties anonymizetagsetting_1json__JsonSchema="http://json.schemastore.org/jovo-language-model" properties_4launchsettings_1json__JsonSchema="" /></VisualStudio></ProjectExtensions> <ProjectExtensions><VisualStudio><UserProperties properties_4launchsettings_1json__JsonSchema="" /></VisualStudio></ProjectExtensions>
</Project> </Project>

View File

@ -27,7 +27,7 @@ namespace IRaCIS.Core.API
options.AddInterceptors(new QueryWithNoLockDbCommandInterceptor()); options.AddInterceptors(new QueryWithNoLockDbCommandInterceptor());
options.UseProjectables(); //options.UseProjectables();
//options.AddInterceptors(new AuditingInterceptor(configuration.GetSection("ConnectionStrings:RemoteNew").Value)); //options.AddInterceptors(new AuditingInterceptor(configuration.GetSection("ConnectionStrings:RemoteNew").Value));

View File

@ -17,9 +17,9 @@
"Endpoint": "https://oss-cn-shanghai.aliyuncs.com", "Endpoint": "https://oss-cn-shanghai.aliyuncs.com",
"AccessKeyId": "LTAI5tKvzs7ed3UfSpNk3xwQ", "AccessKeyId": "LTAI5tKvzs7ed3UfSpNk3xwQ",
"AccessKeySecret": "zTIceGEShlZDGnLrCFfIGFE7TXVRio", "AccessKeySecret": "zTIceGEShlZDGnLrCFfIGFE7TXVRio",
"BucketName": "zy-sir-test-store", "BucketName": "zyypacs",
"RoleArn": "acs:ram::1899121822495495:role/oss-upload", "RoleArn": "acs:ram::1899121822495495:role/oss-upload",
"ViewEndpoint": "https://zy-sir-test-store.oss-cn-shanghai.aliyuncs.com", "ViewEndpoint": "https://zyypacs.oss-cn-shanghai.aliyuncs.com",
"Region": "oss-cn-shanghai" "Region": "oss-cn-shanghai"
}, },
"BasicSystemConfig": { "BasicSystemConfig": {

View File

@ -5,7 +5,6 @@ using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Application.Service; using IRaCIS.Core.Application.Service;
using IRaCIS.Core.Domain.Share; using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure; using IRaCIS.Core.Infrastructure;
using Microsoft.EntityFrameworkCore.SqlServer.Query.Internal;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;

View File

@ -64,7 +64,6 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Aliyun.OSS.SDK.NetCore" Version="2.13.0" /> <PackageReference Include="Aliyun.OSS.SDK.NetCore" Version="2.13.0" />
<PackageReference Include="EntityFrameworkCore.Projectables" Version="3.0.4" />
<PackageReference Include="EntityFrameworkCore.Triggered" Version="3.2.2" /> <PackageReference Include="EntityFrameworkCore.Triggered" Version="3.2.2" />
<PackageReference Include="FreeSpire.Doc" Version="11.6.0" /> <PackageReference Include="FreeSpire.Doc" Version="11.6.0" />
<PackageReference Include="Hangfire.Core" Version="1.8.5" /> <PackageReference Include="Hangfire.Core" Version="1.8.5" />

View File

@ -3,6 +3,7 @@ using IRaCIS.Application.Contracts;
using IRaCIS.Core.Application.Contracts; using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Application.ViewModel; using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Domain.Models; using IRaCIS.Core.Domain.Models;
using IRaCIS.Core.Domain.Share;
namespace IRaCIS.Core.Application.Service namespace IRaCIS.Core.Application.Service
{ {
@ -20,6 +21,11 @@ namespace IRaCIS.Core.Application.Service
CreateMap<FrontAuditConfig, FrontAuditConfigAddOrEdit>().ReverseMap(); CreateMap<FrontAuditConfig, FrontAuditConfigAddOrEdit>().ReverseMap();
CreateMap<EmailNoticeConfigAddOrEdit, EmailNoticeConfig>().ReverseMap(); CreateMap<EmailNoticeConfigAddOrEdit, EmailNoticeConfig>().ReverseMap();
CreateMap<EmailNoticeUserType, EmailUserTypeDto>();
var trialId = Guid.Empty; var trialId = Guid.Empty;
CreateMap<EmailNoticeConfig, TrialSelectEmailNoticeConfigView>().IncludeBase<EmailNoticeConfig, EmailNoticeConfigView>() CreateMap<EmailNoticeConfig, TrialSelectEmailNoticeConfigView>().IncludeBase<EmailNoticeConfig, EmailNoticeConfigView>()
.ForMember(o => o.IsHaveSelected, t => t.MapFrom(u => u.TrialEmailNoticeConfigList.Any(c => c.TrialId == trialId && c.SysEmailNoticeConfigId == u.Id))) .ForMember(o => o.IsHaveSelected, t => t.MapFrom(u => u.TrialEmailNoticeConfigList.Any(c => c.TrialId == trialId && c.SysEmailNoticeConfigId == u.Id)))
@ -28,13 +34,14 @@ namespace IRaCIS.Core.Application.Service
CreateMap<EmailNoticeConfig, EmailNoticeConfigView>() CreateMap<EmailNoticeConfig, EmailNoticeConfigView>()
.ForMember(t => t.EmailNoticeUserList, u => u.MapFrom(c => c.EmailNoticeUserTypeList)); .ForMember(t => t.EmailNoticeUserList, u => u.MapFrom(c => c.EmailNoticeUserTypeList));
CreateMap<Dictionary, DicView>()
.ForMember(t => t.ParentCode, u => u.MapFrom(c => c.Parent.Code));
CreateMap<SystemBasicData, SystemBasicDataView>(); CreateMap<SystemBasicData, SystemBasicDataView>();
var isEn_Us = false; var isEn_Us = false;
CreateMap<SystemBasicData, SystemBasicDataSelect>() CreateMap<SystemBasicData, SystemBasicDataSelect>()
.ForMember(o => o.ParentCode, t => t.MapFrom(u => u.Parent.Code)) .ForMember(o => o.ParentCode, t => t.MapFrom(u => u.Parent.Code))
.ForMember(o => o.Value, t => t.MapFrom(u => isEn_Us? u.Value:u.ValueCN)); .ForMember(o => o.Value, t => t.MapFrom(u => isEn_Us ? u.Value : u.ValueCN));
CreateMap<SystemBasicDataAddOrEdit, SystemBasicData>().ReverseMap(); CreateMap<SystemBasicDataAddOrEdit, SystemBasicData>().ReverseMap();
@ -51,7 +58,7 @@ namespace IRaCIS.Core.Application.Service
CreateMap<Dictionary, BasicDicSelectCopy>() CreateMap<Dictionary, BasicDicSelectCopy>()
.ForMember(o => o.ParentChildCodeEnum, t => t.MapFrom(u => u.Parent.ChildCodeEnum)) .ForMember(o => o.ParentChildCodeEnum, t => t.MapFrom(u => u.Parent.ChildCodeEnum))
.ForMember(o => o.Value, t => t.MapFrom(u => isEn_Us? u.Value : u.ValueCN )) .ForMember(o => o.Value, t => t.MapFrom(u => isEn_Us ? u.Value : u.ValueCN))
.ForMember(o => o.ParentCode, t => t.MapFrom(u => u.Parent.Code)); .ForMember(o => o.ParentCode, t => t.MapFrom(u => u.Parent.Code));
CreateMap<Dictionary, BasicDicSelect>() CreateMap<Dictionary, BasicDicSelect>()

View File

@ -571,6 +571,8 @@ namespace IRaCIS.Core.Application.Service
SqlParameter[] paravalue = new SqlParameter[] { SqlParameter[] paravalue = new SqlParameter[] {
new SqlParameter("@para",para) new SqlParameter("@para",para)
}; };
//https://learn.microsoft.com/zh-tw/ef/core/querying/sql-queries
jsonDataValueDic[item.Key] = string.Join(",", _frontAuditConfigRepository._dbContext.Database.SqlQuery<ForeignKey>(sql, paravalue).Select(x => x.Text).ToList()); jsonDataValueDic[item.Key] = string.Join(",", _frontAuditConfigRepository._dbContext.Database.SqlQuery<ForeignKey>(sql, paravalue).Select(x => x.Text).ToList());
} }
} }

View File

@ -8,7 +8,6 @@ using Panda.DynamicWebApi.Attributes;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Memory;
using IRaCIS.Core.Infra.Common.Cache;
using Microsoft.Identity.Client; using Microsoft.Identity.Client;
using static IRaCIS.Core.Domain.Share.StaticData; using static IRaCIS.Core.Domain.Share.StaticData;
using IRaCIS.Core.Application.ViewModel; using IRaCIS.Core.Application.ViewModel;

View File

@ -63,6 +63,9 @@ namespace IRaCIS.Application.Services
[AllowAnonymous] [AllowAnonymous]
public async Task<IResponseOutput> TestDistributedLock( ) public async Task<IResponseOutput> TestDistributedLock( )
{ {
_repository.Where<User>().Select(t => t.FullName).FirstOrDefault();
Console.WriteLine($"我进来了当前值是:" + IntValue); Console.WriteLine($"我进来了当前值是:" + IntValue);
_logger.LogWarning($"我进来了当前值是:" + IntValue); _logger.LogWarning($"我进来了当前值是:" + IntValue);

View File

@ -10,9 +10,6 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -6,7 +6,6 @@
using System; using System;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Collections.Generic; using System.Collections.Generic;
using EntityFrameworkCore.Projectables;
using System.Linq; using System.Linq;
namespace IRaCIS.Core.Domain.Models namespace IRaCIS.Core.Domain.Models

View File

@ -9,7 +9,6 @@ using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using EntityFrameworkCore.Projectables;
namespace IRaCIS.Core.Domain.Models namespace IRaCIS.Core.Domain.Models
{ {
@ -324,7 +323,7 @@ namespace IRaCIS.Core.Domain.Models
public Guid? BeforeConvertedTaskId { get; set; } public Guid? BeforeConvertedTaskId { get; set; }
[Projectable] [NotMapped]
[JsonIgnore] [JsonIgnore]
public bool IsConvertedTask => BeforeConvertedTaskId != null || IsHistoryConvertedTask|| Subject.SubjectVisitTaskList.Where(t => t.TrialReadingCriterionId == TrialReadingCriterionId public bool IsConvertedTask => BeforeConvertedTaskId != null || IsHistoryConvertedTask|| Subject.SubjectVisitTaskList.Where(t => t.TrialReadingCriterionId == TrialReadingCriterionId
&& t.DoctorUserId == DoctorUserId && t.BeforeConvertedTaskId != null && t.DoctorUserId == DoctorUserId && t.BeforeConvertedTaskId != null

View File

@ -1,4 +1,3 @@
using EntityFrameworkCore.Projectables;
using IRaCIS.Core.Domain.Share; using IRaCIS.Core.Domain.Share;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -60,9 +59,6 @@ namespace IRaCIS.Core.Domain.Models
[Projectable]
public string TranslateValue( string value, string valueCN,bool isCN) => isCN?valueCN:value;
} }
} }

View File

@ -1,4 +1,3 @@
using EntityFrameworkCore.Projectables;
using IRaCIS.Core.Domain.Share; using IRaCIS.Core.Domain.Share;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -51,7 +50,7 @@ namespace IRaCIS.Core.Domain.Models
[StringLength(100)] [StringLength(100)]
public string LastName { get; set; } = string.Empty; public string LastName { get; set; } = string.Empty;
[Projectable] [NotMapped]
public string FullName => LastName + " / " + FirstName; public string FullName => LastName + " / " + FirstName;
public int Sex { get; set; } public int Sex { get; set; }

View File

@ -8,15 +8,16 @@
<OutputPath>..\bin</OutputPath> <OutputPath>..\bin</OutputPath>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="EntityFrameworkCore.Projectables.Abstractions" Version="3.0.4" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\IRaCIS.Core.Domain.Share\IRaCIS.Core.Domain.Share.csproj" /> <ProjectReference Include="..\IRaCIS.Core.Domain.Share\IRaCIS.Core.Domain.Share.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Using Include=" Newtonsoft.Json;" /> <Using Include=" Newtonsoft.Json;" />

View File

@ -2,7 +2,6 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using EntityFrameworkCore.Projectables;
using IRaCIS.Core.Domain.Share; using IRaCIS.Core.Domain.Share;
namespace IRaCIS.Core.Domain.Models namespace IRaCIS.Core.Domain.Models
@ -93,7 +92,8 @@ namespace IRaCIS.Core.Domain.Models
/// </summary> /// </summary>
public bool AutoCutNextTask { get; set; } = false; public bool AutoCutNextTask { get; set; } = false;
[Projectable] public string FullName => LastName + " / " + FirstName; [NotMapped]
public string FullName => LastName + " / " + FirstName;
//[Projectable] public string FullName => $"{LastName} / {FirstName}"; //[Projectable] public string FullName => $"{LastName} / {FirstName}";
} }

View File

@ -0,0 +1,15 @@
-- 查询指定 code 的记录及其父项
SELECT *
FROM Dictionary
WHERE code = 'BusinessModule'
UNION
-- 查询指定 code 的记录及其子项
SELECT t.*
FROM Dictionary t
INNER JOIN (
SELECT Id
FROM Dictionary
WHERE code = 'BusinessModule'
) AS selected ON t.ParentId = selected.Id;

View File

@ -56,7 +56,7 @@ namespace IRaCIS.Core.Infra.EFCore
dbConn = conn; dbConn = conn;
conn.Open(); conn.Open();
DbCommand cmd = conn.CreateCommand(); DbCommand cmd = conn.CreateCommand();
if (facade.IsSqlServer()) if (facade.IsRelational())
{ {
cmd.CommandText = sql; cmd.CommandText = sql;
CombineParams(ref cmd, parameters); CombineParams(ref cmd, parameters);

View File

@ -18,7 +18,9 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="EFCore.BulkExtensions" Version="7.1.6" /> <PackageReference Include="EFCore.BulkExtensions" Version="7.1.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="7.0.12" />
<PackageReference Include="EntityFrameworkCore.Exceptions.SqlServer" Version="6.0.3.2" /> <PackageReference Include="EntityFrameworkCore.Exceptions.SqlServer" Version="6.0.3.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.12" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
<PackageReference Include="Microsoft.Extensions.Localization.Abstractions" Version="7.0.12" /> <PackageReference Include="Microsoft.Extensions.Localization.Abstractions" Version="7.0.12" />

View File

@ -1,9 +1,12 @@
using EFCore.BulkExtensions; using AutoMapper.Internal;
using EFCore.BulkExtensions;
using IRaCIS.Core.Domain.Models; using IRaCIS.Core.Domain.Models;
using IRaCIS.Core.Infrastructure; using IRaCIS.Core.Infrastructure;
using IRaCIS.Core.Infrastructure.Extention; using IRaCIS.Core.Infrastructure.Extention;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query;
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Reflection; using System.Reflection;
@ -83,10 +86,10 @@ namespace IRaCIS.Core.Infra.EFCore
} }
} }
public static async Task EntityVerifyAsync<T>(this IRepository<T> _entityRepository, Guid? entitydId = null,params EntityVerifyExp<T>[] verify) where T : Entity public static async Task EntityVerifyAsync<T>(this IRepository<T> _entityRepository, Guid? entitydId = null, params EntityVerifyExp<T>[] verify) where T : Entity
{ {
if (entitydId==null) if (entitydId == null)
{ {
foreach (var verifyItem in verify.Where(t => t.verifyType != VerifyEnum.OnlyUpdate && t.IsVerify)) foreach (var verifyItem in verify.Where(t => t.verifyType != VerifyEnum.OnlyUpdate && t.IsVerify))
{ {
@ -122,7 +125,7 @@ namespace IRaCIS.Core.Infra.EFCore
///注意 模型标注了 ConcurrencyCheck的属性这样的实体不适合用部分字段更新ef生成的更新sql会自动带上ConcurrencyCheck的属性条件 ///注意 模型标注了 ConcurrencyCheck的属性这样的实体不适合用部分字段更新ef生成的更新sql会自动带上ConcurrencyCheck的属性条件
/// <summary>EntityState.Detached的实体 修改 部分字段</summary> /// <summary>EntityState.Detached的实体 修改 部分字段</summary>
public static void EntityModifyPartialFiled<T>(this IRaCISDBContext _dbContext,T waitModifyEntity, Expression<Func<T, T>> updateFactory) where T : Entity public static void EntityModifyPartialFiled<T>(this IRaCISDBContext _dbContext, T waitModifyEntity, Expression<Func<T, T>> updateFactory) where T : Entity
{ {
var entityEntry = _dbContext.Entry(waitModifyEntity); var entityEntry = _dbContext.Entry(waitModifyEntity);
//entityEntry.State = EntityState.Detached; //entityEntry.State = EntityState.Detached;
@ -153,19 +156,22 @@ namespace IRaCIS.Core.Infra.EFCore
#region 不走EF 跟踪机制的删除 更新 以及批量操作 #region 不走EF 跟踪机制的删除 更新 以及批量操作
/// <summary>批量删除相当于原生sql 没用EF跟踪方式所有查询出来再删除 浪费性能)</summary> /// <summary>批量删除相当于原生sql 没用EF跟踪方式所有查询出来再删除 浪费性能)</summary>
public static async Task<bool> BatchDeleteNoTrackingAsync<T>(this IRaCISDBContext _dbContext,Expression<Func<T, bool>> deleteFilter) where T : Entity public static async Task<bool> BatchDeleteNoTrackingAsync<T>(this IRaCISDBContext _dbContext, Expression<Func<T, bool>> deleteFilter) where T : Entity
{ {
if (deleteFilter == null) throw new ArgumentNullException(nameof(deleteFilter)); if (deleteFilter == null) throw new ArgumentNullException(nameof(deleteFilter));
return await _dbContext.Set<T>().IgnoreQueryFilters().Where(deleteFilter).BatchDeleteAsync() > 0; return await _dbContext.Set<T>().IgnoreQueryFilters().Where(deleteFilter).ExecuteDeleteAsync() > 0;
} }
/// <summary>批量更新相当于原生sql 没用EF跟踪方式所有查询出来再更新 浪费性能)</summary> /// <summary>批量更新相当于原生sql 没用EF跟踪方式所有查询出来再更新 浪费性能)</summary>
public static async Task<bool> BatchUpdateNoTrackingAsync<T>(this IRaCISDBContext _dbContext,Expression<Func<T, bool>> where, Expression<Func<T, T>> updateFactory,Guid updateUserId) where T : Entity public static async Task<bool> BatchUpdateNoTrackingAsync<T>(this IRaCISDBContext _dbContext, Expression<Func<T, bool>> where, Expression<Func<T, T>> updateFactory, Guid updateUserId) where T : Entity
{ {
if (where == null) throw new ArgumentNullException(nameof(where)); if (where == null) throw new ArgumentNullException(nameof(where));
#region batch delete bug
var bindings = ((MemberInitExpression)updateFactory.Body).Bindings.ToList(); var bindings = ((MemberInitExpression)updateFactory.Body).Bindings.ToList();
var hasPropNameList = bindings.Select(t => t.Member.Name).ToList(); var hasPropNameList = bindings.Select(t => t.Member.Name).ToList();
@ -193,12 +199,74 @@ namespace IRaCIS.Core.Infra.EFCore
var factory = Expression.Lambda<Func<T, T>>(member, Expression.Parameter(typeof(T), "x")); var factory = Expression.Lambda<Func<T, T>>(member, Expression.Parameter(typeof(T), "x"));
return await _dbContext.Set<T>().IgnoreQueryFilters().Where(where).BatchUpdateAsync(factory).ConfigureAwait(false) > 0; return await _dbContext.Set<T>().IgnoreQueryFilters().Where(where).BatchUpdateAsync(factory).ConfigureAwait(false) > 0;
#endregion
#region efcore 7
//Dictionary<string, object> propValues = new Dictionary<string, object>();
//// 获取表达式体的 MemberInitExpression
//var memberInitExpr = (MemberInitExpression)updateFactory.Body;
//// 获取初始化的绑定信息
//var bindings = memberInitExpr.Bindings.ToList();
//var hasPropNameList = bindings.Select(t => t.Member.Name).ToList();
//// 遍历绑定信息
//foreach (MemberAssignment binding in bindings)
//{
// // 获取属性名
// string propName = binding.Member.Name;
// // 获取属性值,需要对表达式进行编译和调用
// var propValue = Expression.Lambda(binding.Expression).Compile().DynamicInvoke();
// // 现在,你可以访问属性名和属性值
// propValues.Add(propName, propValue);
//}
//if (typeof(IAuditUpdate).IsAssignableFrom(typeof(T)))
//{
// if (!hasPropNameList.Contains(nameof(IAuditUpdate.UpdateTime)))
// {
// propValues.Add(nameof(IAuditUpdate.UpdateTime), DateTime.Now);
// }
// if (!hasPropNameList.Contains(nameof(IAuditUpdate.UpdateUserId)))
// {
// propValues.Add(nameof(IAuditUpdate.UpdateUserId), updateUserId);
// }
//}
//return await _dbContext.Set<T>().IgnoreQueryFilters().Where(where).ExecuteUpdateAsync(s => s.SetProperty(t => "UpdateTime", u => "").se).ConfigureAwait(false) > 0;
////return await _dbContext.Set<T>().IgnoreQueryFilters().Where(where).ExecuteUpdateAsync(propValues.SetProperties<T>()).ConfigureAwait(false) > 0;
#endregion
} }
#endregion #endregion
} }

View File

@ -12,7 +12,6 @@ using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using IRaCIS.Core.Domain.Share; using IRaCIS.Core.Domain.Share;
using EFCore.BulkExtensions;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
namespace IRaCIS.Core.Infra.EFCore namespace IRaCIS.Core.Infra.EFCore

View File

@ -10,7 +10,6 @@ using IRaCIS.Core.Domain.Models;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.ChangeTracking;
using AutoMapper.QueryableExtensions; using AutoMapper.QueryableExtensions;
using EFCore.BulkExtensions;
using IRaCIS.Core.Domain.Share; using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure; using IRaCIS.Core.Infrastructure;
using IRaCIS.Core.Infrastructure.Extention; using IRaCIS.Core.Infrastructure.Extention;
@ -194,7 +193,6 @@ namespace IRaCIS.Core.Infra.EFCore
_dbContext.EntityModifyPartialFiled(entity, updateFactory); _dbContext.EntityModifyPartialFiled(entity, updateFactory);
await SaveChangesAsync(autoSave); await SaveChangesAsync(autoSave);
} }

View File

@ -1,18 +0,0 @@

namespace IRaCIS.Core.Infra.Common.Cache
{
/// <summary>
/// 缓存类型
/// </summary>
public enum CacheType
{
/// <summary>
/// 内存缓存
/// </summary>
Memory,
/// <summary>
/// Redis缓存
/// </summary>
Redis
}
}

View File

@ -1,107 +0,0 @@
using System;
using System.Threading.Tasks;
namespace IRaCIS.Core.Infra.Common.Cache
{
/// <summary>
/// 缓存接口
/// </summary>
public interface ICache
{
/// <summary>
/// 用于在 key 存在时删除 key
/// </summary>
/// <param name="key">键</param>
long Del(params string[] key);
/// <summary>
/// 用于在 key 存在时删除 key
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
Task<long> DelAsync(params string[] key);
/// <summary>
/// 用于在 key 模板存在时删除
/// </summary>
/// <param name="pattern">key模板</param>
/// <returns></returns>
Task<long> DelByPatternAsync(string pattern);
/// <summary>
/// 检查给定 key 是否存在
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
bool Exists(string key);
/// <summary>
/// 检查给定 key 是否存在
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
Task<bool> ExistsAsync(string key);
/// <summary>
/// 获取指定 key 的值
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
string Get(string key);
/// <summary>
/// 获取指定 key 的值
/// </summary>
/// <typeparam name="T">byte[] 或其他类型</typeparam>
/// <param name="key">键</param>
/// <returns></returns>
T Get<T>(string key);
/// <summary>
/// 获取指定 key 的值
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
Task<string> GetAsync(string key);
/// <summary>
/// 获取指定 key 的值
/// </summary>
/// <typeparam name="T">byte[] 或其他类型</typeparam>
/// <param name="key">键</param>
/// <returns></returns>
Task<T> GetAsync<T>(string key);
/// <summary>
/// 设置指定 key 的值所有写入参数object都支持string | byte[] | 数值 | 对象
/// </summary>
/// <param name="key">键</param>
/// <param name="value">值</param>
bool Set(string key, object value);
/// <summary>
/// 设置指定 key 的值所有写入参数object都支持string | byte[] | 数值 | 对象
/// </summary>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <param name="expire">有效期</param>
bool Set(string key, object value, TimeSpan expire);
/// <summary>
/// 设置指定 key 的值所有写入参数object都支持string | byte[] | 数值 | 对象
/// </summary>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <returns></returns>
Task<bool> SetAsync(string key, object value);
/// <summary>
/// 设置指定 key 的值所有写入参数object都支持string | byte[] | 数值 | 对象
/// </summary>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <param name="expire">有效期</param>
/// <returns></returns>
Task<bool> SetAsync(string key, object value, TimeSpan expire);
}
}

View File

@ -1,127 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;
namespace IRaCIS.Core.Infra.Common.Cache
{
/// <summary>
/// 内存缓存
/// </summary>
public class MemoryCache : ICache
{
private readonly IMemoryCache _memoryCache;
public MemoryCache(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
public long Del(params string[] key)
{
foreach(var k in key)
{
_memoryCache.Remove(k);
}
return key.Length;
}
public Task<long> DelAsync(params string[] key)
{
foreach (var k in key)
{
_memoryCache.Remove(k);
}
return Task.FromResult((long)key.Length);
}
public async Task<long> DelByPatternAsync(string pattern)
{
if (string.IsNullOrEmpty(pattern))
return default;
pattern = Regex.Replace(pattern, @"\{.*\}", "(.*)");
var keys = GetAllKeys().Where(k => Regex.IsMatch(k, pattern));
if(keys != null && keys.Count() > 0)
{
return await DelAsync(keys.ToArray());
}
return default;
}
public bool Exists(string key)
{
return _memoryCache.TryGetValue(key, out _);
}
public Task<bool> ExistsAsync(string key)
{
return Task.FromResult(_memoryCache.TryGetValue(key, out _));
}
public string Get(string key)
{
return _memoryCache.Get(key)?.ToString();
}
public T Get<T>(string key)
{
return _memoryCache.Get<T>(key);
}
public Task<string> GetAsync(string key)
{
return Task.FromResult(Get(key));
}
public Task<T> GetAsync<T>(string key)
{
return Task.FromResult(Get<T>(key));
}
public bool Set(string key, object value)
{
_memoryCache.Set(key, value);
return true;
}
public bool Set(string key, object value, TimeSpan expire)
{
_memoryCache.Set(key, value, expire);
return true;
}
public Task<bool> SetAsync(string key, object value)
{
Set(key, value);
return Task.FromResult(true);
}
public Task<bool> SetAsync(string key, object value, TimeSpan expire)
{
Set(key, value, expire);
return Task.FromResult(true);
}
private List<string> GetAllKeys()
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
var entries = _memoryCache.GetType().GetField("_entries", flags).GetValue(_memoryCache);
var cacheItems = entries as IDictionary;
var keys = new List<string>();
if (cacheItems == null) return keys;
foreach (DictionaryEntry cacheItem in cacheItems)
{
keys.Add(cacheItem.Key.ToString());
}
return keys;
}
}
}

View File

@ -1,88 +0,0 @@
using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace IRaCIS.Core.Infra.Common.Cache
{
/// <summary>
/// Redis缓存
/// </summary>
public class RedisCache : ICache
{
public long Del(params string[] key)
{
return RedisHelper.Del(key);
}
public Task<long> DelAsync(params string[] key)
{
return RedisHelper.DelAsync(key);
}
public async Task<long> DelByPatternAsync(string pattern)
{
if (string.IsNullOrEmpty(pattern))
return default;
pattern = Regex.Replace(pattern, @"\{.*\}", "*");
var keys = (await RedisHelper.KeysAsync(pattern));
if(keys != null && keys.Length > 0)
{
return await RedisHelper.DelAsync(keys);
}
return default;
}
public bool Exists(string key)
{
return RedisHelper.Exists(key);
}
public Task<bool> ExistsAsync(string key)
{
return RedisHelper.ExistsAsync(key);
}
public string Get(string key)
{
return RedisHelper.Get(key);
}
public T Get<T>(string key)
{
return RedisHelper.Get<T>(key);
}
public Task<string> GetAsync(string key)
{
return RedisHelper.GetAsync(key);
}
public Task<T> GetAsync<T>(string key)
{
return RedisHelper.GetAsync<T>(key);
}
public bool Set(string key, object value)
{
return RedisHelper.Set(key, value);
}
public bool Set(string key, object value, TimeSpan expire)
{
return RedisHelper.Set(key, value, expire);
}
public Task<bool> SetAsync(string key, object value)
{
return RedisHelper.SetAsync(key, value);
}
public Task<bool> SetAsync(string key, object value, TimeSpan expire)
{
return RedisHelper.SetAsync(key, value, expire);
}
}
}

View File

@ -10,7 +10,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="AutoMapper" Version="12.0.1" /> <PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="CSRedisCore" Version="3.8.671" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.12" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.12" />
<PackageReference Include="SharpCompress" Version="0.34.1" /> <PackageReference Include="SharpCompress" Version="0.34.1" />
<PackageReference Include="SharpZipLib" Version="1.4.2" /> <PackageReference Include="SharpZipLib" Version="1.4.2" />