开发者

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

开发者 https://www.devze.com 2023-03-18 13:32 出处:网络
I\'m attempting to create a transaction to wrap around several LINQ to SQL SubmitChanges() calls. Code

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 t开发者_Python百科o 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 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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号