// POST: odata/Roles public async Task<IHttpActionResult> Post(Role role) { if (!ModelState.IsValid) { return BadRequest(ModelState); } // Get the list of claim ids var newClaims = role.Claims.Select(x => x.Id); role.Claims = new List<Claim>(); // We need to attach the existing claims from the database and not from the client role.Claims.AddRange(db.Claims.Where(x => newClaims.Contains(x.Id))); db.Roles.Add(role); try { await db.SaveChangesAsync(); } catch (DbUpdateException) { if (RoleExists(role.Id)) { return Conflict(); } throw; } return Created(role); }
// PUT: odata/Roles(5) public async Task<IHttpActionResult> Put([FromODataUri] string key, Role newRole) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var existingRole = db.Roles.Find(key); if (existingRole == null) { return NotFound(); } db.Entry(existingRole).Collection(x => x.Claims).Load(); var claimIds = newRole.Claims.Select(x => x.Id).ToList(); newRole.Claims = new List<Claim>(); // Remove claims not in the list existingRole.Claims.RemoveAll(x => !claimIds.Contains(x.Id)); // Find the ids of the claims we need to add var existingClaimIds = new HashSet<Guid>(existingRole.Claims.Select(x => x.Id)); var claimIdsToAdd = claimIds.Where(x => !existingClaimIds.Contains(x)); // Add the claims to the newRole foreach (var claim in db.Claims.Where(x => claimIdsToAdd.Contains(x.Id))) { existingRole.Claims.Add(claim); } // Overwrite the existing newRole values to the new newRole values db.Entry(existingRole).CurrentValues.SetValues(newRole); try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!RoleExists(key)) { return NotFound(); } throw; } return Updated(newRole); }