Merge branch 'Test_IRC_Net8' of https://gitea.frp.extimaging.com/XCKJ/irc-netcore-api into Test_IRC_Net8
continuous-integration/drone/push Build is passing Details

Test_IRC_Net8
he 2025-08-11 10:37:33 +08:00
commit c01d3cbd14
21 changed files with 61042 additions and 112 deletions

View File

@ -7,10 +7,10 @@
} }
}, },
"ConnectionStrings": { "ConnectionStrings": {
//"RemoteNew": "Server=101.132.193.237,1434;Database=Prod_IRC;User ID=sa;Password=zhanying@2021;TrustServerCertificate=true", "RemoteNew": "Server=101.132.193.237,1434;Database=Prod_IRC;User ID=sa;Password=zhanying@2021;TrustServerCertificate=true",
//"Hangfire": "Server=101.132.193.237,1434;Database=Prod_IRC_Hangfire;User ID=sa;Password=zhanying@2021;TrustServerCertificate=true" "Hangfire": "Server=101.132.193.237,1434;Database=Prod_IRC_Hangfire;User ID=sa;Password=zhanying@2021;TrustServerCertificate=true"
"RemoteNew": "Server=prod_mssql_standard,1433;Database=Prod_IRC;User ID=sa;Password=zhanying@2021;TrustServerCertificate=true", //"RemoteNew": "Server=prod_mssql_standard,1433;Database=Prod_IRC;User ID=sa;Password=zhanying@2021;TrustServerCertificate=true",
"Hangfire": "Server=prod_mssql_standard,1433;Database=Prod_IRC_Hangfire;User ID=sa;Password=zhanying@2021;TrustServerCertificate=true" //"Hangfire": "Server=prod_mssql_standard,1433;Database=Prod_IRC_Hangfire;User ID=sa;Password=zhanying@2021;TrustServerCertificate=true"
}, },
"ObjectStoreService": { "ObjectStoreService": {
"ObjectStoreUse": "AliyunOSS", "ObjectStoreUse": "AliyunOSS",

View File

@ -0,0 +1,194 @@
using FellowOakDicom;
using FellowOakDicom.Media;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IRaCIS.Core.Application.Helper
{
public class StudyDIRInfo
{
public Guid SubjectVisitId { get; set; }
// Study
public Guid DicomStudyId { get; set; }
public string PatientId { get; set; }
public string PatientName { get; set; }
public string PatientBirthDate { get; set; }
public string PatientSex { get; set; }
public string StudyInstanceUid { get; set; }
public string StudyId { get; set; }
public string DicomStudyDate { get; set; }
public string DicomStudyTime { get; set; }
public string AccessionNumber { get; set; }
public string StudyDescription { get; set; }
// Series
public string SeriesInstanceUid { get; set; }
public string Modality { get; set; }
public string DicomSeriesDate { get; set; }
public string DicomSeriesTime { get; set; }
public int SeriesNumber { get; set; }
public string SeriesDescription { get; set; }
// Instance
public Guid InstanceId { get; set; }
public string SopInstanceUid { get; set; }
public string SOPClassUID { get; set; }
public int InstanceNumber { get; set; }
public string MediaStorageSOPClassUID { get; set; }
public string MediaStorageSOPInstanceUID { get; set; }
public string TransferSytaxUID { get; set; }
}
public static class DicomDIRHelper
{
public static async Task<Dictionary<string, string>> GenerateStudyDIRAndUploadAsync(List<StudyDIRInfo> list, string ossFolder, IOSSService _oSSService)
{
var dic = new Dictionary<string, string>();
var mappings = new List<string>();
int index = 1;
var dicomDir = new DicomDirectory();
foreach (var item in list.OrderBy(t => t.SeriesNumber).ThenBy(t => t.InstanceNumber))
{
var dicomUid = DicomUID.Enumerate().FirstOrDefault(uid => uid.UID == item.TransferSytaxUID);
if (dicomUid != null)
{
var ts = DicomTransferSyntax.Query(dicomUid);
var dataset = new DicomDataset(ts)
{
{ DicomTag.PatientID, item.PatientId ?? string.Empty },
{ DicomTag.PatientName, item.PatientName ?? string.Empty },
{ DicomTag.PatientBirthDate, item.PatientBirthDate ?? string.Empty },
{ DicomTag.PatientSex, item.PatientSex ?? string.Empty },
{ DicomTag.StudyInstanceUID, item.StudyInstanceUid ?? string.Empty },
{ DicomTag.StudyID, item.StudyId ?? string.Empty },
{ DicomTag.StudyDate, item.DicomStudyDate ?? string.Empty },
{ DicomTag.StudyTime, item.DicomStudyTime ?? string.Empty },
{ DicomTag.AccessionNumber, item.AccessionNumber ?? string.Empty },
{ DicomTag.StudyDescription, item.StudyDescription ?? string.Empty },
{ DicomTag.SeriesInstanceUID, item.SeriesInstanceUid ?? string.Empty },
{ DicomTag.Modality, item.Modality ?? string.Empty },
{ DicomTag.SeriesDate, item.DicomSeriesDate ?? string.Empty },
{ DicomTag.SeriesTime, item.DicomSeriesTime ?? string.Empty },
{ DicomTag.SeriesNumber, item.SeriesNumber.ToString() ?? string.Empty },
{ DicomTag.SeriesDescription, item.SeriesDescription ?? string.Empty },
{ DicomTag.SOPInstanceUID, item.SopInstanceUid ?? string.Empty },
{ DicomTag.SOPClassUID, item.SOPClassUID ?? string.Empty },
{ DicomTag.InstanceNumber, item.InstanceNumber.ToString() ?? string.Empty },
{ DicomTag.MediaStorageSOPClassUID, item.MediaStorageSOPClassUID ?? string.Empty },
{ DicomTag.MediaStorageSOPInstanceUID, item.MediaStorageSOPInstanceUID ?? string.Empty },
{ DicomTag.TransferSyntaxUID, item.TransferSytaxUID ?? string.Empty },
};
var dicomFile = new DicomFile(dataset);
// 文件名递增格式IM_00001, IM_00002, ...
string filename = $@"IMAGE/IM_{index:D5}"; // :D5 表示补足5位
mappings.Add($"{filename} => {item.InstanceId}");
dic.Add(item.InstanceId.ToString(), Path.GetFileName(filename));
dicomDir.AddFile(dicomFile, filename);
index++;
}
}
//有实际的文件
if (mappings.Count > 0)
{
#region 写入临时路径
var tempFilePath = Path.GetTempFileName();
// 保存 DICOMDIR 到临时文件 不能直接写入到流种
await dicomDir.SaveAsync(tempFilePath);
using (var memoryStream = new MemoryStream(File.ReadAllBytes(tempFilePath)))
{
// 重置流位置
memoryStream.Position = 0;
await _oSSService.UploadToOSSAsync(memoryStream, ossFolder, "DICOMDIR", false);
}
//清理临时文件
File.Delete(tempFilePath);
#endregion
#region 映射上传
// 将映射写入内存流
var mappingText = string.Join(Environment.NewLine, mappings);
await using var mappingStream = new MemoryStream(Encoding.UTF8.GetBytes(mappingText));
await _oSSService.UploadToOSSAsync(mappingStream, ossFolder, $"Download_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}", false);
#endregion
}
return dic;
}
public static StudyDIRInfo ReadDicomDIRInfo(DicomFile dicomFile)
{
var dataset = dicomFile.Dataset;
var info = new StudyDIRInfo
{
PatientId = dataset.GetSingleValueOrDefault(DicomTag.PatientID, string.Empty),
PatientName = dataset.GetSingleValueOrDefault(DicomTag.PatientName, string.Empty),
PatientBirthDate = dataset.GetSingleValueOrDefault(DicomTag.PatientBirthDate, string.Empty),
PatientSex = dataset.GetSingleValueOrDefault(DicomTag.PatientSex, string.Empty),
StudyInstanceUid = dataset.GetSingleValueOrDefault(DicomTag.StudyInstanceUID, string.Empty),
StudyId = dataset.GetSingleValueOrDefault(DicomTag.StudyID, string.Empty),
DicomStudyDate = dataset.GetSingleValueOrDefault(DicomTag.StudyDate, string.Empty),
DicomStudyTime = dataset.GetSingleValueOrDefault(DicomTag.StudyTime, string.Empty),
AccessionNumber = dataset.GetSingleValueOrDefault(DicomTag.AccessionNumber, string.Empty),
StudyDescription = dataset.GetSingleValueOrDefault(DicomTag.StudyDescription, string.Empty),
SeriesInstanceUid = dataset.GetSingleValueOrDefault(DicomTag.SeriesInstanceUID, string.Empty),
Modality = dataset.GetSingleValueOrDefault(DicomTag.Modality, string.Empty),
DicomSeriesDate = dataset.GetSingleValueOrDefault(DicomTag.SeriesDate, string.Empty),
DicomSeriesTime = dataset.GetSingleValueOrDefault(DicomTag.SeriesTime, string.Empty),
SeriesNumber = dataset.GetSingleValueOrDefault(DicomTag.SeriesNumber, 1),
SeriesDescription = dataset.GetSingleValueOrDefault(DicomTag.SeriesDescription, string.Empty),
SopInstanceUid = dataset.GetSingleValueOrDefault(DicomTag.SOPInstanceUID, string.Empty),
SOPClassUID = dataset.GetSingleValueOrDefault(DicomTag.SOPClassUID, string.Empty),
InstanceNumber = dataset.GetSingleValueOrDefault(DicomTag.InstanceNumber, 1),
MediaStorageSOPClassUID = dicomFile.FileMetaInfo.GetSingleValueOrDefault(DicomTag.MediaStorageSOPClassUID, string.Empty),
MediaStorageSOPInstanceUID = dicomFile.FileMetaInfo.GetSingleValueOrDefault(DicomTag.MediaStorageSOPInstanceUID, string.Empty),
TransferSytaxUID = dicomFile.FileMetaInfo.GetSingleValueOrDefault(DicomTag.TransferSyntaxUID, string.Empty)
};
return info;
}
}
}

View File

@ -112,6 +112,8 @@ public class AliyunOSSTempToken
public string PreviewEndpoint { get; set; } public string PreviewEndpoint { get; set; }
public string DownloadEndPoint => EndPoint.Insert(EndPoint.IndexOf("//") + 2, BucketName + ".");
} }
[LowerCamelCaseJson] [LowerCamelCaseJson]
@ -145,6 +147,8 @@ public interface IOSSService
public Task DownLoadFromOSSAsync(string ossRelativePath, string localFilePath); public Task DownLoadFromOSSAsync(string ossRelativePath, string localFilePath);
public Task<Stream> GetStreamFromOSSAsync(string ossRelativePath);
public ObjectStoreServiceOptions ObjectStoreServiceOptions { get; set; } public ObjectStoreServiceOptions ObjectStoreServiceOptions { get; set; }
public Task<string> GetSignedUrl(string ossRelativePath); public Task<string> GetSignedUrl(string ossRelativePath);
@ -190,7 +194,7 @@ public class OSSService : IOSSService
/// <returns></returns> /// <returns></returns>
public async Task<string> UploadToOSSAsync(Stream fileStream, string oosFolderPath, string fileRealName, bool isFileNameAddGuid = true) public async Task<string> UploadToOSSAsync(Stream fileStream, string oosFolderPath, string fileRealName, bool isFileNameAddGuid = true)
{ {
GetObjectStoreTempToken(); BackBatchGetToken();
var ossRelativePath = isFileNameAddGuid ? $"{oosFolderPath}/{Guid.NewGuid()}_{fileRealName}" : $"{oosFolderPath}/{fileRealName}"; var ossRelativePath = isFileNameAddGuid ? $"{oosFolderPath}/{Guid.NewGuid()}_{fileRealName}" : $"{oosFolderPath}/{fileRealName}";
@ -280,6 +284,37 @@ public class OSSService : IOSSService
} }
//后端批量上传 或者下载不每个文件获取临时token
private void BackBatchGetToken()
{
if (ObjectStoreServiceOptions.ObjectStoreUse == "AliyunOSS")
{
if (AliyunOSSTempToken == null)
{
GetObjectStoreTempToken();
}
//token 过期了
else if (AliyunOSSTempToken.Expiration.AddSeconds(10) <= DateTime.Now)
{
GetObjectStoreTempToken();
}
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "AWS")
{
if (AWSTempToken == null)
{
GetObjectStoreTempToken();
}
//token 过期了
else if (AWSTempToken.Expiration?.AddSeconds(10) <= DateTime.Now)
{
GetObjectStoreTempToken();
}
}
}
/// <summary> /// <summary>
/// oosFolderPath 不要 "/ "开头 应该: TempFolder/ChildFolder /// oosFolderPath 不要 "/ "开头 应该: TempFolder/ChildFolder
@ -291,7 +326,7 @@ public class OSSService : IOSSService
/// <exception cref="BusinessValidationFailedException"></exception> /// <exception cref="BusinessValidationFailedException"></exception>
public async Task<string> UploadToOSSAsync(string localFilePath, string oosFolderPath, bool isFileNameAddGuid = true) public async Task<string> UploadToOSSAsync(string localFilePath, string oosFolderPath, bool isFileNameAddGuid = true)
{ {
GetObjectStoreTempToken(); BackBatchGetToken();
var localFileName = Path.GetFileName(localFilePath); var localFileName = Path.GetFileName(localFilePath);
@ -361,11 +396,7 @@ public class OSSService : IOSSService
public async Task DownLoadFromOSSAsync(string ossRelativePath, string localFilePath) public async Task DownLoadFromOSSAsync(string ossRelativePath, string localFilePath)
{ {
if (isFirstCall) BackBatchGetToken();
{
GetObjectStoreTempToken();
isFirstCall = false;
}
ossRelativePath = ossRelativePath.TrimStart('/'); ossRelativePath = ossRelativePath.TrimStart('/');
try try
@ -378,14 +409,12 @@ public class OSSService : IOSSService
var _ossClient = new OssClient(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? aliConfig.EndPoint : aliConfig.InternalEndpoint, AliyunOSSTempToken.AccessKeyId, AliyunOSSTempToken.AccessKeySecret, AliyunOSSTempToken.SecurityToken); var _ossClient = new OssClient(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? aliConfig.EndPoint : aliConfig.InternalEndpoint, AliyunOSSTempToken.AccessKeyId, AliyunOSSTempToken.AccessKeySecret, AliyunOSSTempToken.SecurityToken);
// 上传文件
var result = _ossClient.GetObject(aliConfig.BucketName, ossRelativePath); var result = _ossClient.GetObject(aliConfig.BucketName, ossRelativePath);
// 将下载的文件流保存到本地文件 // 将下载的文件流保存到本地文件
using (var fs = File.OpenWrite(localFilePath)) using (var fs = File.OpenWrite(localFilePath))
{ {
result.Content.CopyTo(fs); await result.Content.CopyToAsync(fs);
fs.Close();
} }
} }
@ -449,6 +478,96 @@ public class OSSService : IOSSService
} }
public async Task<Stream> GetStreamFromOSSAsync(string ossRelativePath)
{
BackBatchGetToken();
ossRelativePath = ossRelativePath.TrimStart('/');
try
{
if (ObjectStoreServiceOptions.ObjectStoreUse == "AliyunOSS")
{
var aliConfig = ObjectStoreServiceOptions.AliyunOSS;
var _ossClient = new OssClient(
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? aliConfig.EndPoint : aliConfig.InternalEndpoint,
AliyunOSSTempToken.AccessKeyId,
AliyunOSSTempToken.AccessKeySecret,
AliyunOSSTempToken.SecurityToken
);
var result = _ossClient.GetObject(aliConfig.BucketName, ossRelativePath);
// 将OSS返回的流复制到内存流中并返回
var memoryStream = new MemoryStream();
await result.Content.CopyToAsync(memoryStream);
memoryStream.Position = 0; // 重置位置以便读取
return memoryStream;
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "MinIO")
{
var minIOConfig = ObjectStoreServiceOptions.MinIO;
var minioClient = new MinioClient()
.WithEndpoint($"{minIOConfig.EndPoint}:{minIOConfig.Port}")
.WithCredentials(minIOConfig.AccessKeyId, minIOConfig.SecretAccessKey)
.WithSSL(minIOConfig.UseSSL)
.Build();
var memoryStream = new MemoryStream();
var getObjectArgs = new GetObjectArgs()
.WithBucket(minIOConfig.BucketName)
.WithObject(ossRelativePath)
.WithCallbackStream(stream => stream.CopyToAsync(memoryStream));
await minioClient.GetObjectAsync(getObjectArgs);
memoryStream.Position = 0;
return memoryStream;
}
else if (ObjectStoreServiceOptions.ObjectStoreUse == "AWS")
{
var awsConfig = ObjectStoreServiceOptions.AWS;
var credentials = new SessionAWSCredentials(
AWSTempToken.AccessKeyId,
AWSTempToken.SecretAccessKey,
AWSTempToken.SessionToken
);
var clientConfig = new AmazonS3Config
{
RegionEndpoint = RegionEndpoint.USEast1,
UseHttp = true,
};
var amazonS3Client = new AmazonS3Client(credentials, clientConfig);
var getObjectRequest = new Amazon.S3.Model.GetObjectRequest
{
BucketName = awsConfig.BucketName,
Key = ossRelativePath
};
var response = await amazonS3Client.GetObjectAsync(getObjectRequest);
var memoryStream = new MemoryStream();
await response.ResponseStream.CopyToAsync(memoryStream);
memoryStream.Position = 0;
return memoryStream;
}
else
{
throw new BusinessValidationFailedException("未定义的存储介质类型");
}
}
catch (Exception ex)
{
throw new BusinessValidationFailedException("oss流获取失败! " + ex.Message);
}
}
public async Task<string> GetSignedUrl(string ossRelativePath) public async Task<string> GetSignedUrl(string ossRelativePath)
{ {
GetObjectStoreTempToken(); GetObjectStoreTempToken();
@ -1005,14 +1124,9 @@ public class OSSService : IOSSService
} }
} }
private bool isFirstCall = true;
public async Task<long> GetObjectSizeAsync(string sourcePath) public async Task<long> GetObjectSizeAsync(string sourcePath)
{ {
if (isFirstCall) BackBatchGetToken();
{
GetObjectStoreTempToken();
isFirstCall = false;
}
var objectkey = sourcePath.Trim('/'); var objectkey = sourcePath.Trim('/');

View File

@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace IRaCIS.Core.Application.Helper
{
public static class SafeBussinessHelper
{
public static async Task<bool> RunAsync(Func<Task> func, [CallerMemberName] string caller = "", string errorMsgTitle = "")
{
try
{
await func();
return true;
}
catch (Exception ex)
{
Log.Logger.Error($"【{errorMsgTitle}失败 - {caller}】: {ex.Message}");
return false;
}
}
public static async Task<(bool Success, T? Result)> RunAsync<T>(Func<Task<T>> func, [CallerMemberName] string caller = "", string errorMsgTitle = "")
{
try
{
var result = await func();
return (true, result);
}
catch (Exception ex)
{
Log.Logger.Error($"【{errorMsgTitle}失败 - {caller}】: {ex.Message}");
return (false, default);
}
}
}
}

View File

@ -1111,6 +1111,13 @@
<param name="trialId"></param> <param name="trialId"></param>
<returns></returns> <returns></returns>
</member> </member>
<member name="M:IRaCIS.Core.Application.Service.TrialImageDownloadService.DownloadAndUploadTrialData(System.Guid,IRaCIS.Core.Infra.EFCore.IRepository{IRaCIS.Core.Domain.Models.DicomInstance},IRaCIS.Core.Infra.EFCore.IRepository{IRaCIS.Core.Domain.Models.DicomStudy},IRaCIS.Core.Infra.EFCore.IRepository{IRaCIS.Core.Domain.Models.DicomSeries})">
<summary>
下载影像 维护dir信息 并回传到OSS
</summary>
<param name="trialId"></param>
<returns></returns>
</member>
<member name="T:IRaCIS.Core.Application.Service.AttachmentService"> <member name="T:IRaCIS.Core.Application.Service.AttachmentService">
<summary> <summary>
医生文档关联关系维护 医生文档关联关系维护

View File

@ -1,10 +1,14 @@
using DocumentFormat.OpenXml.EMMA; using DocumentFormat.OpenXml.EMMA;
using FellowOakDicom; using FellowOakDicom;
using FellowOakDicom.Imaging;
using FellowOakDicom.Imaging.Render;
using FellowOakDicom.IO.Buffer;
using IRaCIS.Core.Application.Helper; using IRaCIS.Core.Application.Helper;
using MassTransit; using MassTransit;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using SharpCompress.Common;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -41,12 +45,14 @@ namespace IRaCIS.Core.Application.Service
[AllowAnonymous] [AllowAnonymous]
public async Task<IResponseOutput> DownloadTrialImage(Guid trialId) public async Task<IResponseOutput> DownloadTrialImage(Guid trialId)
{ {
var subjectCodeList = new List<string>() { "05002", "07006", "07026" }; //var subjectCodeList = new List<string>() { "05002", "07006", "07026" };
var downloadInfo = _trialRepository.Where(t => t.Id == trialId).Select(t => new var downloadInfo = _trialRepository.Where(t => t.Id == trialId).Select(t => new
{ {
t.ResearchProgramNo, t.ResearchProgramNo,
VisitList = t.SubjectVisitList.Where(t=>subjectCodeList.Contains(t.Subject.Code)).Select(sv => new VisitList = t.SubjectVisitList
//.Where(t=>subjectCodeList.Contains(t.Subject.Code))
.Select(sv => new
{ {
TrialSiteCode = sv.TrialSite.TrialSiteCode, TrialSiteCode = sv.TrialSite.TrialSiteCode,
SubjectCode = sv.Subject.Code, SubjectCode = sv.Subject.Code,
@ -57,11 +63,11 @@ namespace IRaCIS.Core.Application.Service
u.StudyTime, u.StudyTime,
u.StudyCode, u.StudyCode,
SeriesList = u.SeriesList.Select(z => new SeriesList = u.SeriesList.Where(t => t.IsReading).Select(z => new
{ {
z.Modality, z.Modality,
InstancePathList = z.DicomInstanceList.Select(k => new InstancePathList = z.DicomInstanceList.Where(t => t.IsReading).Select(k => new
{ {
k.Path k.Path
}).ToList() }).ToList()
@ -69,13 +75,13 @@ namespace IRaCIS.Core.Application.Service
}).ToList(), }).ToList(),
NoneDicomStudyList = sv.NoneDicomStudyList.Select(nd => new NoneDicomStudyList = sv.NoneDicomStudyList.Where(t => t.IsReading).Select(nd => new
{ {
nd.Modality, nd.Modality,
nd.StudyCode, nd.StudyCode,
nd.ImageDate, nd.ImageDate,
FileList = nd.NoneDicomFileList.Select(file => new FileList = nd.NoneDicomFileList.Where(t => t.IsReading).Select(file => new
{ {
file.FileName, file.FileName,
file.Path, file.Path,
@ -90,10 +96,15 @@ namespace IRaCIS.Core.Application.Service
var count = downloadInfo.VisitList.SelectMany(t => t.NoneDicomStudyList).SelectMany(t => t.FileList).Count(); var count = downloadInfo.VisitList.SelectMany(t => t.NoneDicomStudyList).SelectMany(t => t.FileList).Count();
var count2 = downloadInfo.VisitList.SelectMany(t => t.StudyList).SelectMany(t => t.SeriesList).SelectMany(t => t.InstancePathList).Count(); var count2 = downloadInfo.VisitList.SelectMany(t => t.StudyList).SelectMany(t => t.SeriesList).SelectMany(t => t.InstancePathList).Count();
Console.WriteLine($"下载总数量:{count}+{count2}={count + count2}");
if (downloadInfo != null) if (downloadInfo != null)
{ {
var downloadJobs = new List<Func<Task>>();
var rootFolder = FileStoreHelper.GetDonwnloadImageFolder(_hostEnvironment); var rootFolder = @"E:\DownloadImage";
//var rootFolder = FileStoreHelper.GetDonwnloadImageFolder(_hostEnvironment);
// 获取无效字符(系统定义的) // 获取无效字符(系统定义的)
string invalidChars = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()); string invalidChars = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
@ -141,8 +152,12 @@ namespace IRaCIS.Core.Application.Service
// 复制文件到相应的文件夹 // 复制文件到相应的文件夹
string destinationPath = Path.Combine(studyDicomFolderPath, Path.GetFileName(instanceInfo.Path)); string destinationPath = Path.Combine(studyDicomFolderPath, Path.GetFileName(instanceInfo.Path));
//加入到下载任务里
downloadJobs.Add(() => _oSSService.DownLoadFromOSSAsync(instanceInfo.Path, destinationPath));
//下载到当前目录 //下载到当前目录
await _oSSService.DownLoadFromOSSAsync(instanceInfo.Path, destinationPath); //await _oSSService.DownLoadFromOSSAsync(instanceInfo.Path, destinationPath);
} }
} }
@ -159,15 +174,59 @@ namespace IRaCIS.Core.Application.Service
{ {
string destinationPath = Path.Combine(studyNoneDicomFolderPath, Path.GetFileName(file.FileName)); string destinationPath = Path.Combine(studyNoneDicomFolderPath, Path.GetFileName(file.FileName));
//加入到下载任务里
downloadJobs.Add(() => _oSSService.DownLoadFromOSSAsync(HttpUtility.UrlDecode(file.Path), destinationPath));
//下载到当前目录 //下载到当前目录
await _oSSService.DownLoadFromOSSAsync(HttpUtility.UrlDecode(file.Path), destinationPath); //await _oSSService.DownLoadFromOSSAsync(HttpUtility.UrlDecode(file.Path), destinationPath);
} }
} }
} }
#region 异步方式处理
int totalCount = downloadJobs.Count;
int downloadedCount = 0;
foreach (var job in downloadJobs)
{
try
{
await job();
}
catch (Exception ex)
{
Console.WriteLine($"下载失败: {ex.Message}");
}
downloadedCount++;
// 每处理50个输出一次进度或最后一个时也输出
if (downloadedCount % 50 == 0 || downloadedCount == totalCount)
{
Console.WriteLine($"已下载 {downloadedCount} / {totalCount} 个文件,完成 {(downloadedCount * 100.0 / totalCount):F2}%");
}
}
#endregion
#region 多线程测试
//const int batchSize = 15;
//int totalCount = downloadJobs.Count;
//int downloadedCount = 0;
//for (int i = 0; i < downloadJobs.Count; i += batchSize)
//{
// var batch = downloadJobs.Skip(i).Take(batchSize).Select(job => job());
// await Task.WhenAll(batch);
// downloadedCount += batch.Count();
// Console.WriteLine($"已下载 {downloadedCount} / {totalCount} 个文件,完成 {(downloadedCount * 100.0 / totalCount):F2}%");
//}
#endregion
} }
@ -176,6 +235,105 @@ namespace IRaCIS.Core.Application.Service
} }
/// <summary>
/// 下载影像 维护dir信息 并回传到OSS
/// </summary>
/// <param name="trialId"></param>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public async Task<IResponseOutput> DownloadAndUploadTrialData(Guid trialId, [FromServices] IRepository<DicomInstance> _instanceRepository,
[FromServices] IRepository<DicomStudy> _studyRepository,
[FromServices] IRepository<DicomSeries> _seriesRepository)
{
var list = await _instanceRepository.Where(t => t.TrialId == trialId && t.SubjectVisitId == Guid.Parse("01000000-0a00-0242-bd20-08dcce543ded" ) && t.DicomStudy.ModalityForEdit == "IVUS")
.Select(t => new { t.SeriesId, t.StudyId, t.Id, t.Path }).ToListAsync();
int totalCount = list.Count;
int dealCount = 0;
foreach (var item in list)
{
var stream = await _oSSService.GetStreamFromOSSAsync(item.Path);
var dicomFile = DicomFile.Open(stream);
// 获取 Pixel Data 标签
var pixelData = DicomPixelData.Create(dicomFile.Dataset);
//获取像素是否为封装形式
var syntax = dicomFile.Dataset.InternalTransferSyntax;
//对于封装像素的文件做转换
if (syntax.IsEncapsulated)
{
// 创建一个新的片段序列
var newFragments = new DicomOtherByteFragment(DicomTag.PixelData);
// 获取每帧数据并封装为单独的片段
for (int n = 0; n < pixelData.NumberOfFrames; n++)
{
var frameData = pixelData.GetFrame(n);
newFragments.Fragments.Add(new MemoryByteBuffer(frameData.Data));
}
// 替换原有的片段序列
dicomFile.Dataset.AddOrUpdate(newFragments);
}
#region 获取dir信息 维护数据库三个表数据
var dirInfo = DicomDIRHelper.ReadDicomDIRInfo(dicomFile);
await _instanceRepository.BatchUpdateNoTrackingAsync(t => t.Id == item.Id,
u => new DicomInstance()
{
IsEncapsulated= syntax.IsEncapsulated,
TransferSytaxUID = dirInfo.TransferSytaxUID,
SOPClassUID = dirInfo.SOPClassUID,
MediaStorageSOPClassUID = dirInfo.MediaStorageSOPClassUID,
MediaStorageSOPInstanceUID = dirInfo.MediaStorageSOPInstanceUID
}, false);
await _seriesRepository.BatchUpdateNoTrackingAsync(t => t.Id == item.SeriesId,
u => new DicomSeries()
{
DicomSeriesDate = dirInfo.DicomSeriesDate,
DicomSeriesTime = dirInfo.DicomSeriesTime,
}, false);
await _studyRepository.BatchUpdateNoTrackingAsync(t => t.Id == item.StudyId,
u => new DicomStudy()
{
DicomStudyDate = dirInfo.DicomStudyDate,
DicomStudyTime = dirInfo.DicomStudyTime
}, false);
#endregion
//保存到内存流
using var memoryStream = new MemoryStream();
dicomFile.Save(memoryStream);
memoryStream.Position = 0;
//获取原始目录 和文件名
var folder = item.Path.Substring(0, item.Path.LastIndexOf('/')).TrimStart('/');
var fileName = Path.GetFileName(item.Path);
//dicomFile.Save($"download_{Guid.NewGuid()}");
await _oSSService.UploadToOSSAsync(memoryStream, folder, fileName, false);
dealCount++;
Console.WriteLine($"{DateTime.Now}已下载 {dealCount} / {totalCount} 个文件,完成 {(dealCount * 100.0 / totalCount):F2}%");
}
return ResponseOutput.Ok();
}
} }
} }

View File

@ -1,4 +1,5 @@
using IRaCIS.Core.Application.Service.ImageAndDoc.DTO; using FellowOakDicom;
using IRaCIS.Core.Application.Service.ImageAndDoc.DTO;
using IRaCIS.Core.Domain.Share; using IRaCIS.Core.Domain.Share;
using Newtonsoft.Json; using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
@ -323,9 +324,14 @@ namespace IRaCIS.Core.Application.Contracts
public string BodyPartExamined { get; set; } = string.Empty; public string BodyPartExamined { get; set; } = string.Empty;
public string DicomStudyDate { get; set; }
public string DicomStudyTime { get; set; }
public List<AddOrUpdateSeriesDto> SeriesList { get; set; } public List<AddOrUpdateSeriesDto> SeriesList { get; set; }
} }
public class AddOrUpdateSeriesDto public class AddOrUpdateSeriesDto
@ -351,6 +357,12 @@ namespace IRaCIS.Core.Application.Contracts
public string TriggerTime { get; set; } = string.Empty; public string TriggerTime { get; set; } = string.Empty;
public string ImageResizePath { get; set; } = string.Empty; public string ImageResizePath { get; set; } = string.Empty;
public string DicomSeriesDate { get; set; }
public string DicomSeriesTime { get; set; }
public List<AddInstanceDto> InstanceList { get; set; } public List<AddInstanceDto> InstanceList { get; set; }
public Guid? VisitTaskId { get; set; } public Guid? VisitTaskId { get; set; }
@ -385,6 +397,17 @@ namespace IRaCIS.Core.Application.Contracts
public string HtmlPath { get; set; } = string.Empty; public string HtmlPath { get; set; } = string.Empty;
public long FileSize { get; set; } public long FileSize { get; set; }
public string SOPClassUID { get; set; }
public string MediaStorageSOPClassUID { get; set; }
public string TransferSytaxUID { get; set; }
public string MediaStorageSOPInstanceUID { get; set; }
public bool IsEncapsulated => DicomTransferSyntax.Lookup(DicomUID.Parse(TransferSytaxUID)).IsEncapsulated;
} }
public class CRCUploadTaskQuery public class CRCUploadTaskQuery
@ -502,7 +525,68 @@ namespace IRaCIS.Core.Application.Contracts
} }
#region 下载重新生成名字
public class ImageDownloadDto
{
public Guid TrialId { get; set; }
public Guid SubjectId { get; set; }
public string SubjectCode { get; set; }
public string TrialSiteCode { get; set; }
public string VisitName { get; set; }
public string TaskBlindName { get; set; }
public Guid VisitId { get; set; }
public List<DownloadDicomStudyDto> StudyList { get; set; }
public List<DownloadNoneDicomStudyDto> NoneDicomStudyList { get; set; }
}
public class DownloadDicomStudyDto
{
public string PatientId { get; set; }
public DateTime? StudyTime { get; set; }
public string StudyCode { get; set; }
public string StudyInstanceUid { get; set; }
public string StudyDIRPath { get; set; }
public List<DownloadDicomSeriesDto> SeriesList { get; set; }
}
public class DownloadDicomSeriesDto
{
public string Modality { get; set; }
public List<DownloadDicomInstanceDto> InstanceList { get; set; }
}
public class DownloadDicomInstanceDto
{
public Guid InstanceId { get; set; }
public string FileName { get; set; }
public string Path { get; set; }
public long? FileSize { get; set; }
}
public class DownloadNoneDicomStudyDto
{
public string Modality { get; set; }
public string StudyCode { get; set; }
public DateTime? ImageDate { get; set; }
public List<DownloadNoneDicomFileDto> FileList { get; set; } = new();
}
public class DownloadNoneDicomFileDto
{
public string FileName { get; set; }
public string Path { get; set; }
public string FileType { get; set; }
public long? FileSize { get; set; }
}
#endregion
public class CRCUploadedStudyQuqry public class CRCUploadedStudyQuqry
{ {
@ -594,6 +678,9 @@ namespace IRaCIS.Core.Application.Contracts
public bool IsKeyImage { get; set; } public bool IsKeyImage { get; set; }
// true 导出阅片null 就是所有影像
public bool? IsExportReading { get; set; }
} }
@ -637,8 +724,14 @@ namespace IRaCIS.Core.Application.Contracts
public long? TotalImageSize { get; set; } public long? TotalImageSize { get; set; }
public long? TotalReadingImageSize { get; set; }
public string TotalImageSizeStr => TotalImageSize.HasValue public string TotalImageSizeStr => TotalImageSize.HasValue
? $"{TotalImageSize.Value / 1024d / 1024d:F3} MB" ? $"{TotalImageSize.Value / 1024d / 1024d:F3} MB"
: "0.000 MB";
public string TotalReadingImageSizeStr => TotalReadingImageSize.HasValue
? $"{TotalReadingImageSize.Value / 1024d / 1024d:F3} MB"
: "0.000 MB"; : "0.000 MB";
public string ImageTypeStr => $"{(IsHaveDicom ? "DICOM" : "")}{(IsHaveNoneDicom&&IsHaveDicom?" , ":"")}{(IsHaveNoneDicom ? "Non-DICOM" : "")}"; public string ImageTypeStr => $"{(IsHaveDicom ? "DICOM" : "")}{(IsHaveNoneDicom&&IsHaveDicom?" , ":"")}{(IsHaveNoneDicom ? "Non-DICOM" : "")}";
@ -692,6 +785,22 @@ namespace IRaCIS.Core.Application.Contracts
? $"{TotalImageSize.Value / SubjectVisitCount / 1024d / 1024d:F3} MB" ? $"{TotalImageSize.Value / SubjectVisitCount / 1024d / 1024d:F3} MB"
: "0.000 MB"; : "0.000 MB";
public long? TotalReadingImageSize { get; set; }
public string TotalReadingImageSizeStr => TotalReadingImageSize.HasValue
? $"{TotalReadingImageSize.Value / 1024d / 1024d:F3} MB"
: "0.000 MB";
public string SubjectReadingImageAVGSizeStr => TotalReadingImageSize.HasValue
? $"{TotalReadingImageSize.Value / SubjectCount / 1024d / 1024d:F3} MB"
: "0.000 MB";
public string SubjectVisitReadingImageAVGSizeStr => TotalReadingImageSize.HasValue
? $"{TotalReadingImageSize.Value / SubjectVisitCount / 1024d / 1024d:F3} MB"
: "0.000 MB";
} }
public class TrialImageDownloadView public class TrialImageDownloadView

View File

@ -1,5 +1,6 @@
using DocumentFormat.OpenXml.EMMA; using DocumentFormat.OpenXml.EMMA;
using FellowOakDicom; using FellowOakDicom;
using FellowOakDicom.Media;
using IRaCIS.Core.Application.Contracts; using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Application.Contracts.Dicom.DTO; using IRaCIS.Core.Application.Contracts.Dicom.DTO;
using IRaCIS.Core.Application.Filter; using IRaCIS.Core.Application.Filter;
@ -14,9 +15,11 @@ using MassTransit;
using MassTransit.Initializers; using MassTransit.Initializers;
using Medallion.Threading; using Medallion.Threading;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using NetTopologySuite.Mathematics;
using Newtonsoft.Json; using Newtonsoft.Json;
using NPOI.SS.Formula.Functions; using NPOI.SS.Formula.Functions;
using System.Data; using System.Data;
using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.Text; using System.Text;
using System.Web; using System.Web;
@ -32,7 +35,7 @@ namespace IRaCIS.Core.Application.Service.ImageAndDoc
} }
[ApiExplorerSettings(GroupName = "Trial")] [ApiExplorerSettings(GroupName = "Trial")]
public class DownloadAndUploadService(IRepository<SystemAnonymization> _systemAnonymizationRepository, public class DownloadAndUploadService(IRepository<SystemAnonymization> _systemAnonymizationRepository, IRepository<DicomStudy> _dicomStudyRepository,
IRepository<VisitTask> _visitTaskRepository, IRepository<VisitTask> _visitTaskRepository,
IRepository<SubjectVisit> _subjectVisitRepository, IRepository<SubjectVisit> _subjectVisitRepository,
IOSSService _oSSService, IOSSService _oSSService,
@ -779,58 +782,137 @@ namespace IRaCIS.Core.Application.Service.ImageAndDoc
var imageType = (isQueryDicom && isQueryNoneDicom) ? ImageType.DicomAndNoneDicom : (isQueryDicom ? ImageType.Dicom : ImageType.NoneDicom); var imageType = (isQueryDicom && isQueryNoneDicom) ? ImageType.DicomAndNoneDicom : (isQueryDicom ? ImageType.Dicom : ImageType.NoneDicom);
var dirDic = new Dictionary<string, string>();
#region DIR处理导出文件名并将对应关系上传到OSS里面存储
//有传输语法值的导出 才生成DIR
if (_subjectVisitRepository.Any(t => t.Id == inQuery.SubjectVisitId && t.StudyList.SelectMany(t => t.InstanceList).Any(c => c.TransferSytaxUID != string.Empty)))
{
var list = _subjectVisitRepository.Where(t => t.Id == inQuery.SubjectVisitId).SelectMany(t => t.StudyList)
.Where(t => isQueryDicom ? inQuery.DicomStudyIdList.Contains(t.Id) : false)
.SelectMany(t => t.InstanceList)
.Select(t => new StudyDIRInfo()
{
DicomStudyId = t.DicomStudy.Id,
PatientId = t.DicomStudy.PatientId,
PatientName = t.DicomStudy.PatientName,
PatientBirthDate = t.DicomStudy.PatientBirthDate,
PatientSex = t.DicomStudy.PatientSex,
StudyInstanceUid = t.StudyInstanceUid,
StudyId = t.DicomStudy.StudyId,
DicomStudyDate = t.DicomStudy.DicomStudyDate,
DicomStudyTime = t.DicomStudy.DicomStudyTime,
AccessionNumber = t.DicomStudy.AccessionNumber,
StudyDescription = t.DicomStudy.Description,
SeriesInstanceUid = t.DicomSerie.SeriesInstanceUid,
Modality = t.DicomSerie.Modality,
DicomSeriesDate = t.DicomSerie.DicomSeriesDate,
DicomSeriesTime = t.DicomSerie.DicomSeriesTime,
SeriesNumber = t.DicomSerie.SeriesNumber,
SeriesDescription = t.DicomSerie.Description,
InstanceId = t.Id,
SopInstanceUid = t.SopInstanceUid,
SOPClassUID = t.SOPClassUID,
InstanceNumber = t.InstanceNumber,
MediaStorageSOPClassUID = t.MediaStorageSOPClassUID,
MediaStorageSOPInstanceUID = t.MediaStorageSOPInstanceUID,
TransferSytaxUID = t.TransferSytaxUID,
}).ToList();
var pathInfo = await _subjectVisitRepository.Where(t => t.Id == inQuery.SubjectVisitId).Select(t => new { t.TrialId, t.SubjectId, VisitId = t.Id }).FirstNotNullAsync();
foreach (var item in list.GroupBy(t => new { t.StudyInstanceUid, t.DicomStudyId }))
{
var ossFolder = $"{pathInfo.TrialId}/Image/{pathInfo.SubjectId}/{pathInfo.VisitId}/{item.Key.StudyInstanceUid}";
var (isSucess, dic) = await SafeBussinessHelper.RunAsync(async () => await DicomDIRHelper.GenerateStudyDIRAndUploadAsync(item.ToList(), ossFolder, _oSSService));
dirDic = dic;
if (isSucess)
{
await _dicomStudyRepository.BatchUpdateNoTrackingAsync(t => t.Id == item.Key.DicomStudyId, u => new DicomStudy() { StudyDIRPath = $"/{ossFolder}/DICOMDIR" });
}
}
}
#endregion
var query = from sv in _subjectVisitRepository.Where(t => t.Id == inQuery.SubjectVisitId) var query = from sv in _subjectVisitRepository.Where(t => t.Id == inQuery.SubjectVisitId)
select new select new ImageDownloadDto()
{ {
TrialId = sv.TrialId, TrialId = sv.TrialId,
SubjectId = sv.SubjectId, SubjectId = sv.SubjectId,
SubjectCode = sv.Subject.Code, SubjectCode = sv.Subject.Code,
TrialSiteCode = sv.TrialSite.TrialSiteCode, TrialSiteCode = sv.TrialSite.TrialSiteCode,
VisitName = sv.VisitName, VisitName = sv.VisitName,
VisitId = sv.Id,
StudyList = sv.StudyList.Where(t => isQueryDicom ? inQuery.DicomStudyIdList.Contains(t.Id) : false) StudyList = sv.StudyList.Where(t => isQueryDicom ? inQuery.DicomStudyIdList.Contains(t.Id) : false)
.Select(u => new .Select(u => new DownloadDicomStudyDto()
{ {
u.PatientId, PatientId = u.PatientId,
u.StudyTime, StudyTime = u.StudyTime,
u.StudyCode, StudyCode = u.StudyCode,
StudyInstanceUid = u.StudyInstanceUid,
StudyDIRPath = u.StudyDIRPath,
SeriesList = u.SeriesList.Select(z => new SeriesList = u.SeriesList.Select(z => new DownloadDicomSeriesDto()
{ {
z.Modality, Modality = z.Modality,
InstanceList = z.DicomInstanceList.Select(k => new InstanceList = z.DicomInstanceList.Select(k => new DownloadDicomInstanceDto()
{ {
k.Path, InstanceId = k.Id,
k.FileSize FileName = string.Empty,
}) Path = k.Path,
}) FileSize = k.FileSize
}).ToList()
}).ToList()
}).ToList(), }).ToList(),
NoneDicomStudyList = sv.NoneDicomStudyList.Where(t => isQueryNoneDicom ? inQuery.NoneDicomStudyIdList.Contains(t.Id) : false) NoneDicomStudyList = sv.NoneDicomStudyList.Where(t => isQueryNoneDicom ? inQuery.NoneDicomStudyIdList.Contains(t.Id) : false)
.Select(nd => new .Select(nd => new DownloadNoneDicomStudyDto()
{ {
nd.Modality, Modality = nd.Modality,
nd.StudyCode, StudyCode = nd.StudyCode,
nd.ImageDate, ImageDate = nd.ImageDate,
FileList = nd.NoneDicomFileList.Select(file => new FileList = nd.NoneDicomFileList.Select(file => new DownloadNoneDicomFileDto()
{ {
file.FileName, FileName = file.FileName,
file.Path, Path = file.Path,
file.FileType, FileType = file.FileType,
file.FileSize, FileSize = file.FileSize
}) }).ToList()
}).ToList() }).ToList()
}; };
var result = query.FirstOrDefault(); var result = query.FirstOrDefault();
foreach (var item in result.StudyList.SelectMany(t => t.SeriesList).SelectMany(t => t.InstanceList))
{
var key = item.InstanceId.ToString();
if (dirDic.ContainsKey(key))
{
item.FileName = dirDic[key];
}
}
var preDownloadInfo = new TrialImageDownload() var preDownloadInfo = new TrialImageDownload()
{ {
Id = NewId.NextSequentialGuid(), Id = NewId.NextSequentialGuid(),
@ -1004,59 +1086,143 @@ namespace IRaCIS.Core.Application.Service.ImageAndDoc
var trialSiteCode = _visitTaskRepository.Where(t => t.Id == taskIdList.FirstOrDefault()).Select(t => t.IsAnalysisCreate ? t.BlindTrialSiteCode : t.Subject.TrialSite.TrialSiteCode).FirstOrDefault() ?? string.Empty; var trialSiteCode = _visitTaskRepository.Where(t => t.Id == taskIdList.FirstOrDefault()).Select(t => t.IsAnalysisCreate ? t.BlindTrialSiteCode : t.Subject.TrialSite.TrialSiteCode).FirstOrDefault() ?? string.Empty;
var dirDic = new Dictionary<string, string>();
#region 在下载前先处理DIR文件
//有传输语法值的导出 才生成DIR
if (_subjectVisitRepository.Any(t => t.SubjectId == inQuery.SubjectId && t.StudyList.SelectMany(t => t.InstanceList).Any(c => c.TransferSytaxUID != string.Empty)))
{
var dirInfolist = _subjectRepository.Where(t => t.Id == inQuery.SubjectId).SelectMany(t => t.SubjectVisitList.Where(t => subjectVisitIdList.Contains(t.Id))).SelectMany(t => t.StudyList)
.Where(t => isQueryDicom ? inQuery.DicomStudyIdList.Contains(t.Id) : false)
.Where(t => info.IsImageFilter ? ("|" + info.CriterionModalitys + "|").Contains("|" + t.ModalityForEdit + "|") : true)
.SelectMany(t => t.InstanceList.Where(t => t.IsReading && t.DicomSerie.IsReading))
.Select(t => new StudyDIRInfo()
{
SubjectVisitId = t.SubjectVisitId,
DicomStudyId = t.DicomStudy.Id,
PatientId = t.DicomStudy.PatientId,
PatientName = t.DicomStudy.PatientName,
PatientBirthDate = t.DicomStudy.PatientBirthDate,
PatientSex = t.DicomStudy.PatientSex,
StudyInstanceUid = t.StudyInstanceUid,
StudyId = t.DicomStudy.StudyId,
DicomStudyDate = t.DicomStudy.DicomStudyDate,
DicomStudyTime = t.DicomStudy.DicomStudyTime,
AccessionNumber = t.DicomStudy.AccessionNumber,
StudyDescription = t.DicomStudy.Description,
SeriesInstanceUid = t.DicomSerie.SeriesInstanceUid,
Modality = t.DicomSerie.Modality,
DicomSeriesDate = t.DicomSerie.DicomSeriesDate,
DicomSeriesTime = t.DicomSerie.DicomSeriesTime,
SeriesNumber = t.DicomSerie.SeriesNumber,
SeriesDescription = t.DicomSerie.Description,
InstanceId = t.Id,
SopInstanceUid = t.SopInstanceUid,
SOPClassUID = t.SOPClassUID,
InstanceNumber = t.InstanceNumber,
MediaStorageSOPClassUID = t.MediaStorageSOPClassUID,
MediaStorageSOPInstanceUID = t.MediaStorageSOPInstanceUID,
TransferSytaxUID = t.TransferSytaxUID,
}).ToList();
var pathInfo = await _subjectRepository.Where(t => t.Id == inQuery.SubjectId).Select(t => new { t.TrialId, SubjectId = t.Id }).FirstNotNullAsync();
foreach (var item in dirInfolist.GroupBy(t => new { t.StudyInstanceUid, t.DicomStudyId }))
{
var visitId = item.First().SubjectVisitId;
var ossFolder = $"{pathInfo.TrialId}/Image/{pathInfo.SubjectId}/{visitId}/{item.Key.StudyInstanceUid}";
var (isSucess, dic) = await SafeBussinessHelper.RunAsync(async () => await DicomDIRHelper.GenerateStudyDIRAndUploadAsync(item.ToList(), ossFolder, _oSSService));
dirDic = dic;
if (isSucess)
{
await _dicomStudyRepository.BatchUpdateNoTrackingAsync(t => t.Id == item.Key.DicomStudyId, u => new DicomStudy() { StudyDIRPath = $"/{ossFolder}/DICOMDIR" });
}
}
}
#endregion
var query = from sv in _subjectRepository.Where(t => t.Id == inQuery.SubjectId).SelectMany(t => t.SubjectVisitList.Where(t => subjectVisitIdList.Contains(t.Id))) var query = from sv in _subjectRepository.Where(t => t.Id == inQuery.SubjectId).SelectMany(t => t.SubjectVisitList.Where(t => subjectVisitIdList.Contains(t.Id)))
//一致性分析,导致查询出来两条数据 //一致性分析,导致查询出来两条数据
join visitTask in _visitTaskRepository.Where(t => taskIdList.Contains(t.Id)) join visitTask in _visitTaskRepository.Where(t => taskIdList.Contains(t.Id))
on sv.Id equals visitTask.SourceSubjectVisitId on sv.Id equals visitTask.SourceSubjectVisitId
select new select new ImageDownloadDto()
{ {
SubjectCode = inQuery.SubjectCode, SubjectCode = inQuery.SubjectCode,
VisitName = sv.VisitName, VisitName = sv.VisitName,
TaskBlindName = visitTask.TaskBlindName, TaskBlindName = visitTask.TaskBlindName,
StudyList = sv.StudyList.Where(t => isQueryDicom ? inQuery.DicomStudyIdList.Contains(t.Id) : false) StudyList = sv.StudyList.Where(t => isQueryDicom ? inQuery.DicomStudyIdList.Contains(t.Id) : false)
.Where(t => info.IsImageFilter ? ("|" + info.CriterionModalitys + "|").Contains("|" + t.ModalityForEdit + "|") : true) .Where(t => info.IsImageFilter ? ("|" + info.CriterionModalitys + "|").Contains("|" + t.ModalityForEdit + "|") : true)
.Select(u => new .Select(u => new DownloadDicomStudyDto()
{ {
u.PatientId, PatientId = u.PatientId,
u.StudyTime, StudyTime = u.StudyTime,
u.StudyCode, StudyCode = u.StudyCode,
StudyInstanceUid = u.StudyInstanceUid,
StudyDIRPath = u.StudyDIRPath,
SeriesList = u.SeriesList.Where(t => t.IsReading).Select(z => new SeriesList = u.SeriesList.Where(t => t.IsReading).Select(z => new DownloadDicomSeriesDto()
{ {
z.Modality, Modality = z.Modality,
InstancePathList = z.DicomInstanceList.Where(t => t.IsReading).Select(k => new InstanceList = z.DicomInstanceList.Where(t => t.IsReading).Select(k => new DownloadDicomInstanceDto()
{ {
k.Path, InstanceId = k.Id,
k.FileSize FileName = string.Empty,
}) Path = k.Path,
}) FileSize = k.FileSize
}).ToList()
}), }).ToList()
}).ToList(),
NoneDicomStudyList = sv.NoneDicomStudyList.Where(t => isQueryNoneDicom ? inQuery.NoneDicomStudyIdList.Contains(t.Id) : false) NoneDicomStudyList = sv.NoneDicomStudyList.Where(t => isQueryNoneDicom ? inQuery.NoneDicomStudyIdList.Contains(t.Id) : false)
.Where(t => info.IsImageFilter ? ("|" + info.CriterionModalitys + "|").Contains("|" + t.Modality + "|") : true) .Where(t => info.IsImageFilter ? ("|" + info.CriterionModalitys + "|").Contains("|" + t.Modality + "|") : true)
.Where(t => t.IsReading) .Where(t => t.IsReading)
.Select(nd => new .Select(nd => new DownloadNoneDicomStudyDto()
{ {
nd.Modality, Modality = nd.Modality,
nd.StudyCode, StudyCode = nd.StudyCode,
nd.ImageDate, ImageDate = nd.ImageDate,
FileList = nd.NoneDicomFileList.Where(t => t.IsReading).Select(file => new FileList = nd.NoneDicomFileList.Where(t => t.IsReading).Select(file => new DownloadNoneDicomFileDto()
{ {
file.FileName, FileName = file.FileName,
file.Path, Path = file.Path,
file.FileType, FileType = file.FileType,
file.FileSize FileSize = file.FileSize
}) }).ToList()
}) }).ToList()
}; };
var result = await query.ToListAsync(); var list = await query.ToListAsync();
foreach (var result in list)
{
foreach (var item in result.StudyList.SelectMany(t => t.SeriesList).SelectMany(t => t.InstanceList))
{
var key = item.InstanceId.ToString();
if (dirDic.ContainsKey(key))
{
item.FileName = dirDic[key];
}
}
}
@ -1071,17 +1237,17 @@ namespace IRaCIS.Core.Application.Service.ImageAndDoc
DownloadStartTime = DateTime.Now, DownloadStartTime = DateTime.Now,
IsSuccess = false, IsSuccess = false,
ImageType = imageType, ImageType = imageType,
VisitName = string.Join(" | ", result.Select(t => t.VisitName).OrderBy(t => t).ToList()), VisitName = string.Join(" | ", list.Select(t => t.VisitName).OrderBy(t => t).ToList()),
NoneDicomStudyCount = result.Sum(t => t.NoneDicomStudyList.Count()), NoneDicomStudyCount = list.Sum(t => t.NoneDicomStudyList.Count()),
DicomStudyCount = result.Sum(t => t.StudyList.Count()), DicomStudyCount = list.Sum(t => t.StudyList.Count()),
ImageCount = result.Sum(t => t.StudyList.Sum(s => s.SeriesList.Sum(s => s.InstancePathList.Count())) + t.NoneDicomStudyList.Sum(s => s.FileList.Count())), ImageCount = list.Sum(t => t.StudyList.Sum(s => s.SeriesList.Sum(s => s.InstanceList.Count())) + t.NoneDicomStudyList.Sum(s => s.FileList.Count())),
ImageSize = result.Sum(t => t.StudyList.Sum(t => t.SeriesList.Sum(s => s.InstancePathList.Sum(i => i.FileSize))) + t.NoneDicomStudyList.Sum(t => t.FileList.Sum(s => s.FileSize)) ImageSize = list.Sum(t => t.StudyList.Sum(t => t.SeriesList.Sum(s => s.InstanceList.Sum(i => i.FileSize))) + t.NoneDicomStudyList.Sum(t => t.FileList.Sum(s => s.FileSize))
) ?? 0 ) ?? 0
}; };
await _trialImageDownloadRepository.AddAsync(preDownloadInfo, true); await _trialImageDownloadRepository.AddAsync(preDownloadInfo, true);
return ResponseOutput.Ok(result, new { PreDownloadId = preDownloadInfo.Id, info.IsReadingTaskViewInOrder }); return ResponseOutput.Ok(list, new { PreDownloadId = preDownloadInfo.Id, info.IsReadingTaskViewInOrder });
} }
/// <summary> /// <summary>
@ -1218,6 +1384,9 @@ namespace IRaCIS.Core.Application.Service.ImageAndDoc
TotalImageSize = t.StudyList.SelectMany(t => t.InstanceList).Sum(t => t.FileSize) + t.NoneDicomStudyList.SelectMany(t => t.NoneDicomFileList).Sum(t => t.FileSize), TotalImageSize = t.StudyList.SelectMany(t => t.InstanceList).Sum(t => t.FileSize) + t.NoneDicomStudyList.SelectMany(t => t.NoneDicomFileList).Sum(t => t.FileSize),
TotalReadingImageSize = t.StudyList.SelectMany(t => t.InstanceList.Where(t => t.IsReading && t.DicomSerie.IsReading)).Sum(t => t.FileSize)
+ t.NoneDicomStudyList.Where(t => t.IsReading).SelectMany(t => t.NoneDicomFileList.Where(t => t.IsReading)).Sum(t => t.FileSize),
//DicomStudyCount = t.StudyList.Count(), //DicomStudyCount = t.StudyList.Count(),
//NoneDicomStudyCount = t.NoneDicomStudyList.Count(), //NoneDicomStudyCount = t.NoneDicomStudyList.Count(),
@ -1249,6 +1418,10 @@ namespace IRaCIS.Core.Application.Service.ImageAndDoc
{ {
SubjectId = g.Key, SubjectId = g.Key,
VisitCount = g.Count(), VisitCount = g.Count(),
ReadingImageSize = g.SelectMany(t => t.NoneDicomStudyList.Where(t => t.IsReading)).SelectMany(t => t.NoneDicomFileList.Where(t => t.IsReading)).Sum(t => t.FileSize)
+ g.SelectMany(t => t.StudyList).SelectMany(t => t.InstanceList.Where(t => t.IsReading && t.DicomSerie.IsReading)).Sum(t => t.FileSize),
ImageSize = g.SelectMany(t => t.NoneDicomStudyList).SelectMany(t => t.NoneDicomFileList).Sum(t => t.FileSize) ImageSize = g.SelectMany(t => t.NoneDicomStudyList).SelectMany(t => t.NoneDicomFileList).Sum(t => t.FileSize)
+ g.SelectMany(t => t.StudyList).SelectMany(t => t.InstanceList).Sum(t => t.FileSize) + g.SelectMany(t => t.StudyList).SelectMany(t => t.InstanceList).Sum(t => t.FileSize)
@ -1261,7 +1434,9 @@ namespace IRaCIS.Core.Application.Service.ImageAndDoc
var totalImageSize = subjectImageList.Sum(t => t.ImageSize); var totalImageSize = subjectImageList.Sum(t => t.ImageSize);
return ResponseOutput.Ok(new TrialImageStatInfo { SubjectCount = subjectCount, SubjectVisitCount = subjectVisitCount, TotalImageSize = totalImageSize }); var totalReadingImageSize = subjectImageList.Sum(t => t.ReadingImageSize);
return ResponseOutput.Ok(new TrialImageStatInfo { SubjectCount = subjectCount, SubjectVisitCount = subjectVisitCount, TotalImageSize = totalImageSize, TotalReadingImageSize = totalReadingImageSize });
} }
@ -1275,6 +1450,8 @@ namespace IRaCIS.Core.Application.Service.ImageAndDoc
public async Task<IResponseOutput> GetExportSubjectVisitImageList(TrialExportImageCommand inCommand) public async Task<IResponseOutput> GetExportSubjectVisitImageList(TrialExportImageCommand inCommand)
{ {
var isExportReading = inCommand.IsExportReading == true;
if (inCommand.IsKeyImage) if (inCommand.IsKeyImage)
{ {
var downloadInfoList = _visitTaskRepository.Where(t => t.TrialId == inCommand.TrialId && (t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global) var downloadInfoList = _visitTaskRepository.Where(t => t.TrialId == inCommand.TrialId && (t.ReadingCategory == ReadingCategory.Visit || t.ReadingCategory == ReadingCategory.Global)
@ -1538,11 +1715,11 @@ namespace IRaCIS.Core.Application.Service.ImageAndDoc
u.StudyTime, u.StudyTime,
u.StudyCode, u.StudyCode,
SeriesList = u.SeriesList.Select(z => new SeriesList = u.SeriesList.Where(t => isExportReading ? t.IsReading : true).Select(z => new
{ {
z.Modality, z.Modality,
InstancePathList = z.DicomInstanceList.Select(k => new InstancePathList = z.DicomInstanceList.Where(t => isExportReading ? t.IsReading : true).Select(k => new
{ {
k.Path k.Path
}) })
@ -1550,13 +1727,13 @@ namespace IRaCIS.Core.Application.Service.ImageAndDoc
}), }),
NoneDicomStudyList = sv.NoneDicomStudyList.Select(nd => new NoneDicomStudyList = sv.NoneDicomStudyList.Where(t => isExportReading ? t.IsReading : true).Select(nd => new
{ {
nd.Modality, nd.Modality,
nd.StudyCode, nd.StudyCode,
nd.ImageDate, nd.ImageDate,
FileList = nd.NoneDicomFileList.Select(file => new FileList = nd.NoneDicomFileList.Where(t => isExportReading ? t.IsReading : true).Select(file => new
{ {
file.FileName, file.FileName,
file.Path, file.Path,

View File

@ -77,4 +77,20 @@ public class DicomInstance : BaseFullDeleteAuditEntity, IEntitySeqId
public string WindowWidth { get; set; } = null!; public string WindowWidth { get; set; } = null!;
public bool IsReading { get; set; } = true; public bool IsReading { get; set; } = true;
#region DIR 增加
public string SOPClassUID { get; set; }
public string MediaStorageSOPClassUID { get; set; }
public string TransferSytaxUID { get; set; }
public string MediaStorageSOPInstanceUID { get; set; }
public bool IsEncapsulated { get; set; }
#endregion
} }

View File

@ -73,5 +73,12 @@ public class DicomSeries : BaseFullDeleteAuditEntity, IEntitySeqId
public string TriggerTime { get; set; } = null!; public string TriggerTime { get; set; } = null!;
public Guid? VisitTaskId { get; set; } public Guid? VisitTaskId { get; set; }
#region DIR 增加
public string DicomSeriesDate { get; set; }
public string DicomSeriesTime { get; set; }
#endregion
} }

View File

@ -102,4 +102,14 @@ public class DicomStudy : BaseFullDeleteAuditEntity, IEntitySeqId
public string Uploader { get; set; } = null!; public string Uploader { get; set; } = null!;
public string ModifyReason { get; set; } public string ModifyReason { get; set; }
#region DIR 增加字段
public string DicomStudyDate { get; set; }
public string DicomStudyTime { get; set; }
public string StudyDIRPath { get; set; }
#endregion
} }

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,114 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace IRaCIS.Core.Infra.EFCore.Migrations
{
/// <inheritdoc />
public partial class dir : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "DicomStudyDate",
table: "DicomStudy",
type: "nvarchar(400)",
maxLength: 400,
nullable: false,
defaultValue: "");
migrationBuilder.AddColumn<string>(
name: "DicomStudyTime",
table: "DicomStudy",
type: "nvarchar(400)",
maxLength: 400,
nullable: false,
defaultValue: "");
migrationBuilder.AddColumn<string>(
name: "DicomSeriesDate",
table: "DicomSeries",
type: "nvarchar(400)",
maxLength: 400,
nullable: false,
defaultValue: "");
migrationBuilder.AddColumn<string>(
name: "DicomSeriesTime",
table: "DicomSeries",
type: "nvarchar(400)",
maxLength: 400,
nullable: false,
defaultValue: "");
migrationBuilder.AddColumn<string>(
name: "MediaStorageSOPClassUID",
table: "DicomInstance",
type: "nvarchar(400)",
maxLength: 400,
nullable: false,
defaultValue: "");
migrationBuilder.AddColumn<string>(
name: "MediaStorageSOPInstanceUID",
table: "DicomInstance",
type: "nvarchar(400)",
maxLength: 400,
nullable: false,
defaultValue: "");
migrationBuilder.AddColumn<string>(
name: "SOPClassUID",
table: "DicomInstance",
type: "nvarchar(400)",
maxLength: 400,
nullable: false,
defaultValue: "");
migrationBuilder.AddColumn<string>(
name: "TransferSytaxUID",
table: "DicomInstance",
type: "nvarchar(400)",
maxLength: 400,
nullable: false,
defaultValue: "");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DicomStudyDate",
table: "DicomStudy");
migrationBuilder.DropColumn(
name: "DicomStudyTime",
table: "DicomStudy");
migrationBuilder.DropColumn(
name: "DicomSeriesDate",
table: "DicomSeries");
migrationBuilder.DropColumn(
name: "DicomSeriesTime",
table: "DicomSeries");
migrationBuilder.DropColumn(
name: "MediaStorageSOPClassUID",
table: "DicomInstance");
migrationBuilder.DropColumn(
name: "MediaStorageSOPInstanceUID",
table: "DicomInstance");
migrationBuilder.DropColumn(
name: "SOPClassUID",
table: "DicomInstance");
migrationBuilder.DropColumn(
name: "TransferSytaxUID",
table: "DicomInstance");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,30 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace IRaCIS.Core.Infra.EFCore.Migrations
{
/// <inheritdoc />
public partial class dir2 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "StudyDIRPath",
table: "DicomStudy",
type: "nvarchar(400)",
maxLength: 400,
nullable: false,
defaultValue: "");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "StudyDIRPath",
table: "DicomStudy");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace IRaCIS.Core.Infra.EFCore.Migrations
{
/// <inheritdoc />
public partial class addIsEncapsulated : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsEncapsulated",
table: "DicomInstance",
type: "bit",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsEncapsulated",
table: "DicomInstance");
}
}
}

View File

@ -930,9 +930,22 @@ namespace IRaCIS.Core.Infra.EFCore.Migrations
b.Property<bool>("IsDeleted") b.Property<bool>("IsDeleted")
.HasColumnType("bit"); .HasColumnType("bit");
b.Property<bool>("IsEncapsulated")
.HasColumnType("bit");
b.Property<bool>("IsReading") b.Property<bool>("IsReading")
.HasColumnType("bit"); .HasColumnType("bit");
b.Property<string>("MediaStorageSOPClassUID")
.IsRequired()
.HasMaxLength(400)
.HasColumnType("nvarchar(400)");
b.Property<string>("MediaStorageSOPInstanceUID")
.IsRequired()
.HasMaxLength(400)
.HasColumnType("nvarchar(400)");
b.Property<int>("NumberOfFrames") b.Property<int>("NumberOfFrames")
.HasColumnType("int"); .HasColumnType("int");
@ -946,6 +959,11 @@ namespace IRaCIS.Core.Infra.EFCore.Migrations
.HasMaxLength(400) .HasMaxLength(400)
.HasColumnType("nvarchar(400)"); .HasColumnType("nvarchar(400)");
b.Property<string>("SOPClassUID")
.IsRequired()
.HasMaxLength(400)
.HasColumnType("nvarchar(400)");
b.Property<Guid>("SeriesId") b.Property<Guid>("SeriesId")
.HasColumnType("uniqueidentifier"); .HasColumnType("uniqueidentifier");
@ -981,6 +999,11 @@ namespace IRaCIS.Core.Infra.EFCore.Migrations
b.Property<Guid>("SubjectVisitId") b.Property<Guid>("SubjectVisitId")
.HasColumnType("uniqueidentifier"); .HasColumnType("uniqueidentifier");
b.Property<string>("TransferSytaxUID")
.IsRequired()
.HasMaxLength(400)
.HasColumnType("nvarchar(400)");
b.Property<Guid>("TrialId") b.Property<Guid>("TrialId")
.HasColumnType("uniqueidentifier"); .HasColumnType("uniqueidentifier");
@ -1057,6 +1080,16 @@ namespace IRaCIS.Core.Infra.EFCore.Migrations
.HasMaxLength(400) .HasMaxLength(400)
.HasColumnType("nvarchar(400)"); .HasColumnType("nvarchar(400)");
b.Property<string>("DicomSeriesDate")
.IsRequired()
.HasMaxLength(400)
.HasColumnType("nvarchar(400)");
b.Property<string>("DicomSeriesTime")
.IsRequired()
.HasMaxLength(400)
.HasColumnType("nvarchar(400)");
b.Property<Guid>("Id") b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier"); .HasColumnType("uniqueidentifier");
@ -1217,6 +1250,16 @@ namespace IRaCIS.Core.Infra.EFCore.Migrations
.HasMaxLength(400) .HasMaxLength(400)
.HasColumnType("nvarchar(400)"); .HasColumnType("nvarchar(400)");
b.Property<string>("DicomStudyDate")
.IsRequired()
.HasMaxLength(400)
.HasColumnType("nvarchar(400)");
b.Property<string>("DicomStudyTime")
.IsRequired()
.HasMaxLength(400)
.HasColumnType("nvarchar(400)");
b.Property<Guid>("Id") b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier"); .HasColumnType("uniqueidentifier");
@ -1285,6 +1328,11 @@ namespace IRaCIS.Core.Infra.EFCore.Migrations
.HasMaxLength(400) .HasMaxLength(400)
.HasColumnType("nvarchar(400)"); .HasColumnType("nvarchar(400)");
b.Property<string>("StudyDIRPath")
.IsRequired()
.HasMaxLength(400)
.HasColumnType("nvarchar(400)");
b.Property<string>("StudyId") b.Property<string>("StudyId")
.IsRequired() .IsRequired()
.HasMaxLength(400) .HasMaxLength(400)

View File

@ -58,7 +58,7 @@ namespace IRaCIS.Core.Infra.EFCore
Task<bool> BatchDeleteNoTrackingAsync(Expression<Func<TEntity, bool>> deleteFilter); Task<bool> BatchDeleteNoTrackingAsync(Expression<Func<TEntity, bool>> deleteFilter);
/// <summary>批量更新相当于原生sql 没用EF跟踪方式所有查询出来再更新 浪费性能)</summary> /// <summary>批量更新相当于原生sql 没用EF跟踪方式所有查询出来再更新 浪费性能)</summary>
Task<bool> BatchUpdateNoTrackingAsync(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, TEntity>> updateFactory); Task<bool> BatchUpdateNoTrackingAsync(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, TEntity>> updateFactory, bool isAutoIncludeTimeAndUser = true);
Task<bool> ExecuteUpdateAsync(Expression<Func<TEntity, bool>> where, Expression<Func<SetPropertyCalls<TEntity>, SetPropertyCalls<TEntity>>> setPropertyCalls); Task<bool> ExecuteUpdateAsync(Expression<Func<TEntity, bool>> where, Expression<Func<SetPropertyCalls<TEntity>, SetPropertyCalls<TEntity>>> setPropertyCalls);

View File

@ -157,7 +157,7 @@ namespace IRaCIS.Core.Infra.EFCore
/// <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, bool isAutoIncludeTimeAndUser = true) where T : Entity
{ {
if (where == null) throw new ArgumentNullException(nameof(where)); if (where == null) throw new ArgumentNullException(nameof(where));
@ -202,7 +202,8 @@ namespace IRaCIS.Core.Infra.EFCore
if (typeof(IAuditUpdate).IsAssignableFrom(typeof(T))) if (typeof(IAuditUpdate).IsAssignableFrom(typeof(T)))
{ {
if (isAutoIncludeTimeAndUser)
{
if (!hasPropNameList.Contains(nameof(IAuditUpdate.UpdateTime))) if (!hasPropNameList.Contains(nameof(IAuditUpdate.UpdateTime)))
{ {
fieldValues.Add(nameof(IAuditUpdate.UpdateTime), DateTime.Now); fieldValues.Add(nameof(IAuditUpdate.UpdateTime), DateTime.Now);
@ -213,6 +214,7 @@ namespace IRaCIS.Core.Infra.EFCore
fieldValues.Add(nameof(IAuditUpdate.UpdateUserId), updateUserId); fieldValues.Add(nameof(IAuditUpdate.UpdateUserId), updateUserId);
} }
} }
}
return await _dbContext.Set<T>().IgnoreQueryFilters().Where(where).ExecuteUpdateAsync(fieldValues).ConfigureAwait(false) > 0; return await _dbContext.Set<T>().IgnoreQueryFilters().Where(where).ExecuteUpdateAsync(fieldValues).ConfigureAwait(false) > 0;
} }

View File

@ -297,10 +297,10 @@ namespace IRaCIS.Core.Infra.EFCore
/// <summary>批量更新相当于原生sql 没用EF跟踪方式所有查询出来再更新 浪费性能)</summary> /// <summary>批量更新相当于原生sql 没用EF跟踪方式所有查询出来再更新 浪费性能)</summary>
public async Task<bool> BatchUpdateNoTrackingAsync(Expression<Func<TEntity, bool>> where, public async Task<bool> BatchUpdateNoTrackingAsync(Expression<Func<TEntity, bool>> where,
Expression<Func<TEntity, TEntity>> updateFactory) Expression<Func<TEntity, TEntity>> updateFactory ,bool isAutoIncludeTimeAndUser = true)
{ {
return await _dbContext.BatchUpdateNoTrackingAsync(where, updateFactory, _userInfo.UserRoleId); return await _dbContext.BatchUpdateNoTrackingAsync(where, updateFactory, _userInfo.UserRoleId, isAutoIncludeTimeAndUser);
} }