public ActionResult <ResponseJson> Post([FromBody] Dtos.UserRoles model) { Service <cm_user_role> urService = new Service <cm_user_role>(); ResponseJson json = new ResponseJson(); try { service.Context.Db.BeginTran(); model.User.joinTime = DateTime.Now; long uid = service.Context.Db.Insertable(model.User).ExecuteReturnIdentity(); if (uid > 0) { foreach (var roleId in model.Roles) { urService.Insert(new cm_user_role { userId = uid, roleId = roleId }); } } service.Context.Db.CommitTran(); } catch { json.Code = "500"; json.Msg = "新建账号失败!"; service.Context.Db.RollbackTran(); } return(json); }
public ActionResult <ResponseJson> Put(int id, [FromBody] Dtos.UserRoles model) { Service <cm_user_role> urService = new Service <cm_user_role>(); ResponseJson json = new ResponseJson(); List <dynamic> ids = new List <dynamic>(); try { var haved = urService.GetList(o => o.userId == id).ToList(); service.Context.Db.BeginTran(); //修改用户信息 model.User.id = id; service.Update(model.User); //删除用户角色 foreach (var t in haved.Where(o => !model.Roles.Contains(o.roleId))) { ids.Add(t.id); } urService.DeleteList(ids); //增加用户角色 var tids = haved.Select(w => w.roleId).Distinct().ToList(); foreach (var t in model.Roles.Where(o => !tids.Contains(o))) { { urService.Insert(new cm_user_role { userId = id, roleId = t }); } service.Context.Db.CommitTran(); } } catch { json.Code = "500"; json.Msg = "新建账号失败!"; } return(json); }