I open a transaction in EF by calling:

db.Database.BeginTransaction() 

I do some things further, I want to perform operations with a large number of inserts through BulkCopy, but in such a way that if there were errors in EF or BC, everything would roll back.

Can this be done?

Tried to feed BC db.Database.CurrentTransaction , but does not accept ...

    2 answers 2

    It's not very clear why you get CurrentTransaction - to check if a transaction has been created?

    You need to declare a transaction, get it when opening a transaction:

     public DbContextTransaction DbTransaction { set; get; } DbTransaction=db.Database.BeginTransaction(); 

    If there are no errors, commit it:

     DbTransaction.Commit(); 

    If there are errors - roll back:

     DbTransaction.Rollback(); 
    • Is this object able to accept SqlBulkCopy? As far as I know, he only accepts SqlTransaction - iluxa1810
    • As I understand it, when executing, SqlBulkCopy can take a transaction as one of the attributes, judging by similar issues, it should not be passed to the open transaction itself, but to its UnderlyingTransaction. - minamoto

    HERE already knowledge of SQL Server is needed. If I’m not mistaken, Bulk should be an atomic operation and overlaid as one transaction (you can only set up a transaction configuration of up to 6 of them in MS SQL), which is hello to its rollback if it leads to an error. Therefore, there is nothing to commit.