how to Create a Transactionscope between saving a file and inserting a record in DB in C#

后端 未结 2 710
粉色の甜心
粉色の甜心 2021-01-21 18:23

I have a problem, for saving a file and inserting a record in DB in a TransactionScope; Means saving file and inserting record, must depend together = or both or neither. Can an

相关标签:
2条回答
  • 2021-01-21 19:03
    try
    {
        // Start DB Transaction
        // Save To DAtabase code
        // Save To File Code
        // Commit DB Transaction
    }
    catch
    {
        // Rollback DB Transaction
    }
    

    Please notice Sequence of DB should be first then Saving to the file.

    0 讨论(0)
  • 2021-01-21 19:19

    Transactional NTFS

    One of the coolest parts about Transactional NTFS is that it can work with a large number of other transactional technologies. Because TxF uses the new Kernel Transaction Manager (KTM) features, and because the new KTM can work directly with the Microsoft® Distributed Transaction Coordinator (DTC), any technology that can work with DTC as a transaction coordinator can use transacted file operations within a single transaction. This means that you can now enlist transacted file operations within the same transaction as SQL operations, Web service calls via WS-AtomicTransaction, Windows Communication Foundation services via the OleTransactionProtocol, or even transacted MSMQ operations.

    MSDN link

    Alpha FS provides Transaction NTFS in .NET. see Alphaleonis.Win32.Filesystem.KernelTransaction(Transaction transaction). You can get the current transaction by Transaction.Current

    using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew))
    {
        //KernelTransaction is in AlphaFS
        KernelTransaction kt = new KernelTransaction(Transaction.Current);
    
        //Append "hello" to text file named "text.txt"
        Alphaleonis.Win32.Filesystem.File.WriteAllText(kt, "text.txt", "hello");
    
        //No text appended because exception will be thrown
        throw new Exception("oops");
    
        ts.Complete();
    }
    
    0 讨论(0)
提交回复
热议问题