Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL Transaction when Transaction is type Table<Transaction>

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...

like image 777
Jaymz Avatar asked Dec 11 '25 22:12

Jaymz


1 Answers

If the Transaction property from DataContext is being hidden by your DbContext class, just cast:

((DataContext) context).Transaction = trans;

That way Transaction is resolved by the compiler to DataContext.Transaction instead of DbContext.Transaction.

Alternatively you could use a separate variable, which could be useful if you have several such calls to make:

DataContext vanillaContext = context;
vanillaContext.Transaction = trans;

(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.)

like image 180
Jon Skeet Avatar answered Dec 14 '25 12:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!