Ignore TransactionScope for specific query

安稳与你 提交于 2019-12-02 18:59:14
habermanm

If you wrap your log call inside of another transaction scope with the suppress option enabled, transaction scope will not be used.

public override int SaveChanges() {
    try {
        return base.SaveChanges();
    } catch (Exception ex) {
        using (var scope = new TransactionScope(TransactionScopeOption.Suppress)) {
            LogRepo.Log(message); // stuff to log from the context
        }

        throw;
    }
}

Just my initial thought, but you need to put your LogRepo on it's own DataContext (DC2) so that the surrounding TransactionScope (with DC1) won't roll it back when it's not committed.

Basically, you need to make your logging self-contained and atomic.

EDIT In looking at it some more, it seems to me that if you moved your Logging out from the SaveChanges into the catch() on DoSomething(), your logging would work. But, your logging still needs to be self-contained and atomic.

I found one solution that I'm not really happy with, but seems to work. TransactionScope apparently only affects the current thread, so logging using a new thread seems to work ok.

public override int SaveChanges() {
    try {
        return base.SaveChanges();
    } catch (Exception ex) {

        string message = /*stuff to log from the context*/;
        new Thread(msg => {    

            LogRepo.Log(msg);

        }).Start(message);

        throw;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!