EF 分布式事务的使用

此生再无相见时 提交于 2020-01-21 05:16:01
using (JDDbContext dbContext = new JDDbContext())
{
    using (TransactionScope trans = new TransactionScope())
    {
        User userNew1 = new User()
        {
            Account = "Admin",
            State = 0,
            CompanyId = 2031,
            CompanyName = "地府",
            CreateTime = DateTime.Now,
            CreatorId = 1,
            Email = "1111111@qq.com",
            LastLoginTime = null,
            LastModifierId = 0,
            LastModifyTime = DateTime.Now,
            Mobile = "18664876671",
            Name = "啦啦啦32fdsdfds",
            Password = "12356789",
            UserType = 1
        };
        dbContext.Set<User>().Add(userNew1);
        dbContext.SaveChanges();

        SysLog sysLog = new SysLog()
        {
            CreateTime = DateTime.Now,
            CreatorId = userNew1.Id,
            LastModifierId = 0,
            LastModifyTime = DateTime.Now,
            Detail = "12345678",
            Introduction = "sadsfghj",
            LogType = 1,
            UserName = "zhangsanan2zhangsanan2zhangsanan2zhangsanan2zhangsanan2zhangsanan2"
        };
        dbContext.Set<SysLog>().Add(sysLog);
        dbContext.SaveChanges();

        trans.Complete();//能执行这个,就表示成功了;
    }
}
using (JDDbContext dbContext1 = new JDDbContext())
using (JDDbContext dbContext2 = new JDDbContext())
{
    using (TransactionScope trans = new TransactionScope())
    {
        User userNew1 = new User()
        {
            Account = "Admin",
            State = 0,
            CompanyId = 2031,
            CompanyName = "地府",
            CreateTime = DateTime.Now,
            CreatorId = 1,
            Email = "2528877987@qq.com",
            LastLoginTime = null,
            LastModifierId = 0,
            LastModifyTime = DateTime.Now,
            Mobile = "18664876671",
            Name = "开导开导开导",
            Password = "12356789",
            UserType = 1
        };
        dbContext1.Set<User>().Add(userNew1);
        dbContext1.SaveChanges();

        SysLog sysLog = new SysLog()
        {
            CreateTime = DateTime.Now,
            CreatorId = userNew1.Id,
            LastModifierId = 0,
            LastModifyTime = DateTime.Now,
            Detail = "12345678",
            Introduction = "sadsfghj",
            LogType = 1,
            UserName = "zhangsanan2zhangsanan2zhangsanan2zhangsanan2333333333"
        };
        dbContext2.Set<SysLog>().Add(sysLog);
        dbContext2.SaveChanges();

        trans.Complete();//能执行这个,就表示成功了;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!