How can I have 2 ADO access methods use the same Transaction?

Posted by KevinDeus on Stack Overflow See other posts from Stack Overflow or by KevinDeus
Published on 2010-05-21T19:39:28Z Indexed on 2010/05/21 19:40 UTC
Read the original article Hit count: 249

Filed under:
|
|
|
|

I'm writing a test to see if my LINQ to Entity statement works.. I'll be using this for others if I can get this concept going..

my intention here is to INSERT a record with ADO, then verify it can be queried with LINQ, and then ROLLBACK the whole thing at the end.

I'm using ADO to insert because I don't want to use the object or the entity model that I am testing. I figure that a plain ADO INSERT should do fine.

problem is.. they both use different types of connections.

is it possible to have these 2 different data access methods use the same TRANSACTION so I can roll it back??

_conn = new SqlConnection(_connectionString);
_conn.Open();

_trans = _conn.BeginTransaction();

var x = new SqlCommand("INSERT INTO Table1(ID, LastName, FirstName, DateOfBirth) values('127', 'test2', 'user', '2-12-1939');", _conn);

x.ExecuteNonQuery();     //So far, so good.  Adding a record to the table.

//at this point, we need to do **_trans.Commit()** here because our Entity code can't use the same connection. Then I have to manually delete in the TestHarness.TearDown..  I'd like to eliminate this step


//(this code is in another object, I'll include it for brevity. Imagine that I passed the connection in)
//check to see if it is there
using (var ctx = new XEntities(_conn)) //can't do this.. _conn is not an EntityConnection! 
{
    var retVal = (from m in ctx.Table1
                  where m.first_name == "test2"
                  where m.last_name == "user"
                  where m.Date_of_Birth == "2-12-1939"
                  where m.ID == 127
                  select m).FirstOrDefault();

     return (retVal != null);
 }

//Do test.. Assert.BlahBlah();

_trans.Rollback();

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about entity