c# - 执行后能够恢复(将文件更新到 Blob 存储)和(通过 EF Core 添加/更新数据库)
问题描述
我的计划是同时发生 2 个动作。如果 1 失败则恢复,但我很难找到它的方法。
操作 1,将文件上传/更新到 blob 存储(通过命名空间
Azure.Storage.Blobs
>public class BlobContainerClient
)操作 2,在 db 上添加/更新记录/行(通过 EF Core)
伪代码是
public async Task<ActionResult> Upload(<parameter-lists>)
{
// authentication
// verify file (name, size, ...)
// PORTION THAT I HAVE DIFFICULTY
// trying to do [database save] and [upload to storage blob] at the same time
// if success, then good. return response
// if [at least 1] fail, then REVERT both processes ([database save] and [upload to storage blob])
}
我愿意接受任何建议。
- 如果他们一个接一个地跑,而我们仍然有能力恢复第一个动作,那也很棒!
============
编辑1,有朋友有这个建议。
- 这似乎是个好主意,但我很好奇
- 如果这个方法有效
- 如果我们可以使用事务回滚或者我们必须手动编码来恢复这两个功能
await RollbackBlobStorageAsync();
和await RollbackDatabaseAsync();
try
{
await Task.WhenAll(
UpdateDatabaseAsync(),
UpdateBlobStorageAsync(),
);
}
catch (DbUpdateException)
{
await RollbackBlobStorageAsync();
}
catch (BlobStorageUpdateException)
{
await RollbackDatabaseAsync();
}
============
我愿意接受任何建议。
- 如果他们一个接一个地跑,而我们仍然有能力恢复第一个动作,那也很棒!
解决方案
实际上你可以使用事务。最好阅读文档文档
谈到您的建议,请记住数据库上下文不是线程安全的。
var tasks = Task.WhenAll(
UpdateDatabaseAsync(),
UpdateBlobStorageAsync(),
);
try{
await tasks;
}
catch(exception ex){
foreach (var inx in tasks.Exception.InnerExceptions)
{
log(inx);
}
}
if(tasks.IsFaulted){
await RollbackBlobStorageAsync();
await RollbackDatabaseAsync();
}
推荐阅读
- sql - 将表中的每一行与其他每一行进行比较,一次且仅一次
- sql - 使用 postgresql 计算 datediff 并产生年数
- odoo - 如何在 Odoo 中定义自定义设置
- git - 如何解决致命:无法访问,CONNECT 后从代理收到 HTTP 代码 400
- mysql - 如何使用用户提交的变量进行查询并保存?
- ios - 从 UITabBarController 模态显示 ViewController 而不隐藏标签栏
- python - 如何使用 Python 从 shell 连接 MySQL 工作台?
- r - 如何创建对用户输入做出反应的反应数据框_
- java - 如何在 Java 中打开带有锚点的 URL?
- python - 如何在 Python 中从 Azure Databricks 插入 Azure SQL 数据库