FreeSql (28) Services

FreeSql achieve four database transactions to use, dirty reads and other matters related methods not yet available. These methods mainly because the major databases, transaction-level engine even more difficult to unify diverse.

Transaction processing data for consistency, operating in the same transaction is a UnitOfWork, either execute all succeed or fail.

Specified transaction object

FreeSql provides a method specified transaction object, the transaction object is exposed to the outside;

orm.Update<xxx>().WithTransaction(指定事务)
    .Set(a => a.Clicks + 1).ExecuteAffrows();

ISelect, IInsert, IUpdate, IDelete, support WithTransaction method.

With thread Affairs

Suppose the user to buy $ 100 worth of merchandise:

The first step: Buckle balance;

Step two: buckle inventory;

The first step is successful, the second step is insufficient inventory to find that the transaction can be rolled back, buckle balance data will not take effect.

//假设已经有了其他wiki页的IFreeSql声明
fsql.Transaction(() => {

    var affrows = fsql.Update<User>().Set(a => a.Wealth - 100)
        .Where(a => a.Wealth >= 100)
        //判断别让用户余额扣成负数
        .ExecuteAffrows();
    if (affrows < 1) {
        throw new Exception("用户余额不足");
        //抛出异常,事务退出
    }

    affrows = fsql.Update<Goods>().Set(a => a.Stock - 1)
        .Where(a => a.Stock > 0)
        //判断别让用库存扣成负数
        .ExecuteAffrows();
    if (affrows < 1) {
        throw new Exception("商品库存不足");
        //抛出异常,回滚事务,事务退出
        //用户余额的扣除将不生效
    }

    //程序执行在此处,说明都扣成功了,事务完成并提交
});

Note the description:

1, database transactions mount thread, each thread can only open one transaction connection, repeat the open thread will get turned transaction;

2, in the course of transaction code, not use asynchronous methods, including database asynchronous method FreeSql provided, otherwise the thread will switch transactions will not take effect;

3, fsql.Transaction mechanism to prevent deadlock 60 seconds, the transaction is not completed, it will be forced to submit another thread (not rolled back), may result in incomplete transactions, but think carefully 60 seconds of the transaction is not completed What causes it? If too little of 60 seconds may be provided in the parameter overloaded method;

We will follow-up on the work unit in the storage mode, and use DbContext affairs.

Guess you like

Origin www.cnblogs.com/FreeSql/p/11531423.html
28