I am a EntityFramework newbie. I am facing a very weird issue. I am not being able to use transaction using a linq to entity query. I have used for DbTransaction as well as TransactionScope. The error occurs as soon as the query is hit. I am using EF 4.3. The context derives from DbContext as usual. I am using the Code First approach.
using (TransactionScope s = new TransactionScope())
{
using(var context = new XYZContext())
{
context.Database.Connection.Open();
Int32 count = (from xyz in context.XYZs
where xyz.Name == "SameName"
select xyz.Name).Count();
Assert.AreEqual(count, 1);
}
}
I have some doubts. I do not want to use the TrasactionScope because I have heard it has performance issues. So how can I use the DbTransaction instead(also throwing error for me)?
Why do I need to open the connection explicitly? When I am ‘newing’ up a context then should it not open the connection automatically for me?
Try flipping your using clauses, and opening your connection before you start the transaction, and use the context to open the transaction. You also need to commit the transaction if your code is making updates.