Question

I have a repository done in EF 4.3 Code First (EF) , and another repository that uses regular SqlCommand (SQLCMD). EF pass the connection object to SQLCMD, so both are using the same connection.

In EF I create an entity, and use the entity Id to do other operation with SQLCMD. Of course the entity must exist, otherwise I get a FK error. It works well, but I need to keep both operations in the same transaction, so both are rolledback if something goes wrong.

If I wrap both in the same TransactionScope it does not work, SQLCMD cannot see the entity created by EF. But if I remove the TransactionScope it works again. The error is always the same, a SQL error about a wrong FK.

I have tried to enable the MSDTC in my computer, but it is still not working. Although this should not be an issue since both use the same connection.

I have noticed, that EF closes the connection after use, so when SQLCMD get it, it has to open it again. Could it be this the problem?

This is Windows 7 x64 Ultimate and SqlServer 2008.

What is the problem? Thanks!

EDIT:

Apparently the problem is that I am using Tasks in SQLCMD. It is not one, it is a succession of them in a chain, I dunno how to approach this using TransactionDependantClone.

Was it helpful?

Solution

EF only closes the connection if it's closed when you run your EF query. If you manually open the connection first (say, by passing an open connection to the context), then EF won't close it. So you can do this and prevent EF from closing the connection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top