EF 事物Transaction简单操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/// <summary>
/// 申请提现
/// </summary>
/// <param name="userId">用户id</param>
/// <param name="amount">提现金额</param>
/// <returns></returns>
public int ApplyTakeCash(int userId, decimal amount)
{
    if(IsExistUser(userId)) return -3; //用户不存在
    using (var context = new MediaDBContext())
    {
        var channelUser = context.ChannelUsers.FirstOrDefault(c => c.UserId == userId);
        if (channelUser == null) return -3;//用户不存在
        var purse = context.BackPurses.FirstOrDefault(c => c.OwnerId == channelUser.LeaderId);
        if (purse == null) return -2; //未绑定银行卡
        if (purse.Balance < amount) return -1; //余额不足
        using (var trans = context.Database.BeginTransaction())
        {
            string description = string.Format("用户【{0}】申请提现【{1}】元金额", channelUser.User.Mobile, amount);
            try
            {
                var model = new BackWithdrawCash
                {
                    Amount = amount,
                    ApplicantId = 0,
                    PurseId = purse.Id,
                    Remark = description
                };
                //添加提现申请记录
                context.BackWithdrawCashs.Add(model);
                //减少提现额度
                purse.Balance = purse.Balance - amount;
                //提交
                int res = context.SaveChanges();
                if (res > 0)
                {
                    //添加日志
                    AddOperateRecord(userId, channelUser.LeaderId, description+"成功");
                    //提交事物
                    trans.Commit();
                    return 1; //提交成功
                }
                //添加日志
                AddOperateRecord(userId, channelUser.LeaderId, description + "失败");
                return 0;//提交失败
            }
            catch (Exception ex)
            {
                Logger.Error("【TradingServices[ApplyTakeCash]】", ex);
                //添加日志
                AddOperateRecord(userId, channelUser.LeaderId, string.Format("【{0}】【{1}】",description,ex.Message));
                //事物回滚
                trans.Rollback();
                return 0; //提交失败
            }
        }
    }
}

  

posted @   大空白纸  阅读(396)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示