I’m attempting to create a transaction to wrap around several LINQ to SQL SubmitChanges() calls.
Code
System.Data.Common.DbTransaction trans = null;
using (DbContext context = new DbContext())
{
context.Connection.Open()
trans = context.Connection.BeginTransaction();
context.Transaction = trans; // <-- ERROR HERE: Cannot be done!
.... // Several calls to delete objects with context.SaveChanges()
trans.Commit();
}
Problem
In our database schema (which pre-dates me, and is heavily tied into the application), we have a table called Transaction.
This means that the Transaction property in the code above is not actually an IDbTransaction type, and I am unable to assign the trans object to context.Transaction. context.Transaction is actually of type Table<Transaction>.
Question
How can I assign a transaction to my context, given the currently unchangeable fact that I have a table named Transaction?
Although I’m familiar with LINQ to SQL, this is the first time for me using a Transaction around multiple calls, so I’m also ready to accept that I may not be doing this the right way in the first place, and that the conflicting table name may not even be an issue…
If the
Transactionproperty fromDataContextis being hidden by yourDbContextclass, just cast:That way
Transactionis resolved by the compiler toDataContext.Transactioninstead ofDbContext.Transaction.Alternatively you could use a separate variable, which could be useful if you have several such calls to make:
(I have no idea whether or not this is the right way to use the transaction by the way – it’s just the way to get around your naming collision.)