A.Ima
A.Ima

Reputation: 266

BeginTransaction(string) in EF6

I want to use a database transaction with the name( a string) in EF 6.

I found aBeginTransaction() method, but it only has a IsolationLevel Parameter: BeginTransaction(IsolationLevel) Is there a way to use a transaction with a string in EF6?

Upvotes: 1

Views: 107

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109119

It's a bit elaborate, but you can use an existing connection + transaction in a DbContext. I adapted the example here to create a named transaction:

using (SqlConnection conn = new SqlConnection(connectionString))
{
    conn.Open();
    using (var trn = conn.BeginTransaction("TransactionName"))
    {
        using (var db = new MyContext(conn, false))
        {
            db.Database.UseTransaction(trn);
            ... // your code here
        }
    }
}

Note that your context class should implement this constructor and that the second parameter (contextOwnsConnection) must be false. Or use a constructor that defaults to false:

public MyContext(DbConnection connection)
    : base(connection, false)
{ }

Upvotes: 2

Related Questions