EF use distributed transactions

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 = "[email protected]",
            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 = "[email protected]",
            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();//能执行这个,就表示成功了;
    }
}
Published 143 original articles · won praise 117 · Views 4199

Guess you like

Origin blog.csdn.net/weixin_41181778/article/details/103940947