在工作单元中实施数据库事务以进行多个保存调用

问题描述

我对工作单元和存储库模式有些陌生。我已经实现了一个,但是现在在保存需要数据库生成值的数据时遇到了一些问题。

以下是模型:

public class Account
{
     [Key]
     [DatabaseGenerated(DatabaseGeneratedOption.None)]
     public long AccountCode { get; set; }

     [required]
     [StringLength(100)]
     public string Title { get; set; }

     [StringLength(500)]
     public string Description { get; set; }

     public long? openingLedgerId { get; set; }

     public Ledger Ledger { get; set; }
}

public class Ledger
{
     [Key]
     public long LedgerId { get; set; }

     public DateTime TransactionDateTime { get; set; }

     public long AccountCode { get; set; }

     public double Debit { get; set; }

     public double Credit { get; set; }
     
     [required]
     public string Narration { get; set; }

     [ForeignKey(nameof(AccountCode))]
     public Account Account { get; set; }
}

现在通过以下方法详细了解创建方法

public void Create(AccountDTO accountDTO)
{
     Account account = new Account
     {
          AccountCode = accountDTO.AccountCode,Title = accountDTO.Title,Description = accountDTO.Description
     };

     account.Ledger = new Ledger
     {
          TransactionDateTime = DateTime.Now,AccountCode = accountDTO.AccountCode,Narration = "opening Transaction",Debit = accountDTO.Debit,Credit = accountDTO.Credit,};

     _unitOfWork.AccountRepository.Insert(account);
     _unitOfWork.LedgerRepository.Insert(account.Ledger);

     account.openingLedgerId = account.Ledger.LedgerId;

     _unitOfWork.Save();
}

此行account.openingLedgerId = account.Ledger.LedgerId;要求在将分类帐保存到数据库生成该值。

那么,在UnitOfWork中处理此问题或处理数据库级别事务的最佳方法是什么?我想到的一件事是在UnitOfWork类中创建两个类似BeginTransaction(); CommitTransaction();方法,并在此类情况下显式调用它们。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)