title: This SqlTransaction has completed; it is no longer usable. Entity Framework Code First
body: <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Data.SqlClient;
  using System.ComponentModel.DataAnnotations;
  using System.Data.Entity;
  
  namespace SqlEFTester {
      class Program {
          static void Main(string[] args) {
  
              ConnectionManager connectionManager = new ConnectionManager();
              SqlConnection conn = connectionManager.Connection;
              conn.Open();
  
              //BEGIN TRAN
              SqlTransaction tran = conn.BeginTransaction();
  
              //Will do some legacy work using SqlTransaction, so can not use TransactionScope here.
  
              MyContext context = new MyContext(conn);
              List&lt;Inventory&gt; list = context.Inventories.Take(10).ToList();//Just get top 10 Inventories
  
              //COMIT TRAN
              tran.Commit();
  
              Console.WriteLine("Done...");
              Console.ReadLine();
          }
      }
  
  class ConnectionManager {
      public SqlConnection Connection {
          get {
              return new SqlConnection("Data Source=MYSERVER;Initial Catalog=MYDATABASE;Integrated Security=SSPI;");
          }
      }
  }
  
  [Table("Inventory")]
  class Inventory {
      [Key]
      public int InventoryId { get; set; }
  }
  
  class MyContext : DbContext {
      public EmutContext(SqlConnection conn)
          : base(conn, false) {
          //I have to close it, otherwise it will say "EntityConnection can only be constructed with a closed DbConnection."
              base.Database.Connection.Close();
      }
  
      public DbSet&lt;Inventory&gt; Inventories { get; set; }
  }
  </code></pre>
  
  <p>What I am trying to do is execute EF code inside traditional ADO.NET <code>SqlTransaction</code>.</p>
  
  <p>I open a connection and pass the same connection to EF to reuse the connection. By design, I have to close the connection since its complaining </p>
  
  <blockquote>
    <p>EntityConnection can only be constructed with a closed DbConnection.</p>
  </blockquote>
  
  <p>If I run above code I got </p>
  
  <blockquote>
    <p>Transaction has completed.</p>
  </blockquote>
  
  <p>I can not commit. NOTE: I can not use <code>TransactionScope</code> because of legacy code framework we use.</p>