How to assign a transaction with EF4 CodeFirst CTP5 without using TransactionScopes?

I am trying to run functional tests with a live database to make sure my linq queries translate correctly to SQL. I want to do this using transactions, so that one functional test does not affect the other.

The problem is that I cannot find the API method to use transactions correctly. I can get a new DbTransactionone through MyDbContext.Database.Connection.BeginTransaction(), but I just can't find this transaction.

All the documentation I can find about the call BeginTransaction()assigns the transaction object SqlCommandthrough the call cmd.Transactionto the command with which you are executing the actions. However, with EF4 CTP5 it is not possible to access the SqlCommandone used for requests.

Thus, I cannot figure out how to use a transaction that started with BeginTransaction().

I do not want to use objects TransactionScope, mainly because Sql CE 4 does not support them, and I would prefer to use a local database and not cross the network. Sql CE 4 supports transactions received through BeginTransaction(), I just can not understand how with the code first.

Does anyone know how to do this?


Edit : after some emails with Microsoft, it seems that the TransactionScope()calls are for the main use of transactions with EF4. To get TransactionScopeto work with Sql CE, you must explicitly open a database connection before the transaction begins, for example
    [TestMethod]
    public void My_SqlCeScenario ()
    {
        using (var context = new MySQLCeModelContext()) //รŸ derived from DbContext
        {
            ObjectContext objctx = ((IObjectContextAdapter)context).ObjectContext;
            objctx.Connection.Open(); //รŸ Open your connection explicitly
            using (TransactionScope tx = new TransactionScope())
            {

                var product = new Product() { Name = "Vegemite" };
                context.Products.Add(product);
                context.SaveChanges();
            }
            objctx.Connection.Close(); //รŸ close it when done!
        }
    }
+3
source share
2 answers
+2

, :

((EntityConnection)myObjectContext.Connection).StoreConnection.BeginTransaction(...
+1

Source: https://habr.com/ru/post/1787859/


All Articles