在我的应用程序中,我必须同步数据库和外部服务中的更改。如果保存到外部服务时出现错误,则应使用新的更新来恢复对数据库所做的更改。
1. Get entity from database:
var entity = context.Set<MyEntity>().Include(x => x.RelatedEntity).Find(id);
2. Perform changes to database and commit:
entity.Name = "Changed name";
entity.Related.Status = "Approved";
await context.SaveChangesAsync();
3. Save to the external service:
var response = externalService.Save(entity);
4. If there is an error, revert the changes:
if (response.StatusCode != 200)
{
???
}
如何恢复步骤 4 中的原始值?
您可以使用事务来回滚其中的操作。 (请参阅 Microsoft 文档:https://learn.microsoft.com/en-us/ef/core/ saving/transactions)。
示例:
using var transaction = context.Database.BeginTransaction();
// Get entity from database
var entity = context.Set<MyEntity>().Include(x => x.RelatedEntity).Find(id);
// Perform and save changes
entity.Name = "Changed name";
entity.Related.Status = "Approved";
await context.SaveChangesAsync();
// External service call
var response = externalService.Save(entity);
// Only commit the transaction when the when the external service call
// is successful. If not, the transaction will rollback when disposed.
if (response.IsSuccesStatusCode)
{
transaction.Commit();
}