欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

EF 分布式事务的使用

程序员文章站 2022-07-13 22:36:51
...
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();//能执行这个,就表示成功了;
    }
}
相关标签: C# 知识点