public override bool ImportProcess() { try { _coreRepository.Context.Set<CProgramme>().AddRange(Programmes); _coreRepository.Context.SaveChanges(); foreach (var cResourceAccesses in ResourceAccesses) { _coreRepository.Context.Set<CResourceAccess>().AddRange(cResourceAccesses); _coreRepository.Context.SaveChanges(); } _coreRepository.Context.Set<CResources>().AddRange(ResourcesList); _coreRepository.Context.SaveChanges(); } catch (Exception e) { return false; } return true; } 优化一下这段代码
时间: 2024-02-10 08:13:29 浏览: 140
MyApplication_androidservice_android_363ab.con_
可以考虑将循环插入 CResourceAccess 的部分优化为批量插入,可以减少数据库操作次数,提高性能。同时,可以将错误信息记录并返回,方便调试。
优化后的代码如下:
```
public override bool ImportProcess()
{
try
{
_coreRepository.Context.Set<CProgramme>().AddRange(Programmes);
_coreRepository.Context.SaveChanges();
if (ResourceAccesses.Any())
{
List<string> errorLogs = new();
foreach (var cResourceAccesses in ResourceAccesses)
{
_coreRepository.Context.Set<CResourceAccess>().AddRange(cResourceAccesses);
try
{
_coreRepository.Context.SaveChanges();
}
catch (Exception e)
{
errorLogs.Add($"Failed to insert CResourceAccess: {e.Message}");
}
}
if (errorLogs.Any())
{
_errorLogService.SaveErrorLogs(errorLogs, "CResourceAccess");
return false;
}
}
_coreRepository.Context.Set<CResources>().AddRange(ResourcesList);
_coreRepository.Context.SaveChanges();
}
catch (Exception e)
{
return false;
}
return true;
}
```
阅读全文