简体   繁体   中英

How do I disable LINQ to Sql transactions?

I want to make additions to a database, in this case massive amounts of information, with no transactions on my LINQ To SQL model. Does anyone know how to turn off LINQ To SQL transactions on a datacontext or on the submit changes operation?

As far as I can tell, there is no way to disable transactions on insert without changing the recovery mode of the database from full to to simple.

Be careful though, since you can only recover a database with a simple recovery mode to the latest backup and won't be able to apply the transaction logs from transactions that occurred since that backup was performed.

If you can configure a batch size (I know you can with NHibernate, not positive about LINQ to SQL) to something like 100 or more, that can also reduce the round trips to the database which will also increase insert performance.

Since LINQ to SQL will create a transaction if one doesn't exist , the best you can do is create your own transaction with an isolation level that is acceptable to you.

Transaction transaction = new Transaction( IsolationLevel.Chaos );
try
{
    using (var dc = new MyDataContext())
    {
       dc.Transaction = transaction;
       ...
       transaction.Commit();
    }
}
catch
{
    transaction.Rollback();
}

Alternatively, you could submit on each change, ignoring failures. You still get a transaction, but it only wraps each individual change.

foreach (var foo in foos)
{
    using (var context = new MyDataContext())
    {
        context.Foos.InsertOnSubmit(foo);
        try
        {
            context.SubmitChanges();
        }
        catch {}
    }
}

你不能只将DataContext上的Transaction属性设置为null吗?

Set the ConflictMode to ContinueOnConflict and you will be able to commit successfully any changes that work, and you'll have a list at the exception of changes that weren't successful for you to follow up.

db.SubmitChanges(ConflictMode.ContinueOnConflict)

I've got a reference to using this technique to stop errors backing out your submit changes: SandKeySoftware Linq Tutorial

If you have distributed transactions occurring, this should help too:

using(var scope = new TransactionScope(TransactionScopeOption.Suppress))
{
    //linqy stuff here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM