static void Execute_NG() { using (var db = new ManyToManyDbEntities()) { //讀取資料 var users = db.Users.ToList(); var roles = db.Roles.ToList(); var userRoles = db.UserRoles.ToList(); var userRolesAdd = userRoles.Select(x => new UserRole() { UserId = x.UserId, RoleId = x.RoleId }).ToList(); //刪除資料 db.UserRoles.RemoveRange(userRoles); db.Roles.RemoveRange(roles); db.Users.RemoveRange(users); //db.Database.Log = Console.WriteLine; //db.SaveChanges(); Console.WriteLine("Press any key to continue (1)..."); Console.ReadLine(); //加入資料 db.Users.AddRange(users); db.Roles.AddRange(roles); db.UserRoles.AddRange(userRolesAdd); db.Database.Log = Console.WriteLine; db.SaveChanges(); Console.WriteLine("Press any key to continue (2)..."); Console.ReadLine(); } }
static void Execute_OK_With_TransactionScope() { using (var db = new ManyToManyDbEntities()) { //讀取資料 var users = db.Users.ToList(); var roles = db.Roles.ToList(); var userRoles = db.UserRoles.ToList(); var userRolesAdd = userRoles.Select(x => new UserRole() { UserId = x.UserId, RoleId = x.RoleId }).ToList(); using (TransactionScope ts = new TransactionScope()) { //刪除資料 db.UserRoles.RemoveRange(userRoles); db.Roles.RemoveRange(roles); db.Users.RemoveRange(users); db.Database.Log = Console.WriteLine; db.SaveChanges(); Console.WriteLine("Press any key to continue (5)..."); Console.ReadLine(); //加入資料 db.Users.AddRange(users); db.Roles.AddRange(roles); db.UserRoles.AddRange(userRolesAdd); db.Database.Log = Console.WriteLine; db.SaveChanges(); Console.WriteLine("Press any key to continue (6)..."); Console.ReadLine(); ts.Complete(); } } }
static void Execute_OK_With_New_PK() { using (var db = new ManyToManyDbEntities()) { //讀取資料 var users = db.Users.ToList(); var roles = db.Roles.ToList(); var userRoles = db.UserRoles.ToList(); //3 個 table 都給新的 PK 值 var usersAdd = users.Select(x => new User() { UserId = x.UserId + "N", UserName = x.UserName }).ToList(); var rolesAdd = roles.Select(x => new Role() { RoleId = x.RoleId + "N", RoleName = x.RoleName }).ToList(); var userRolesAdd = userRoles.Select(x => new UserRole() { UserId = x.UserId + "N", RoleId = x.RoleId + "N" }).ToList(); //刪除資料 db.UserRoles.RemoveRange(userRoles); db.Roles.RemoveRange(roles); db.Users.RemoveRange(users); //db.Database.Log = Console.WriteLine; //db.SaveChanges(); Console.WriteLine("Press any key to continue (3)..."); Console.ReadLine(); //加入資料 db.Users.AddRange(usersAdd); db.Roles.AddRange(rolesAdd); db.UserRoles.AddRange(userRolesAdd); db.Database.Log = Console.WriteLine; db.SaveChanges(); Console.WriteLine("Press any key to continue (4)..."); Console.ReadLine(); } }