public RepositoryActionResult<Schedule> UpdateSchedule(Schedule e) { try { // you can only update when an expense already exists for this id var existingExpense = _ctx.Schedules.FirstOrDefault(exp => exp.Id == e.Id); if (existingExpense == null) { return new RepositoryActionResult<Schedule>(e, RepositoryActionStatus.NotFound); } // change the original entity status to detached; otherwise, we get an error on attach // as the entity is already in the dbSet // set original entity state to detached _ctx.Entry(existingExpense).State = EntityState.Detached; // attach & save _ctx.Schedules.Attach(e); // set the updated entity state to modified, so it gets updated. _ctx.Entry(e).State = EntityState.Modified; var result = _ctx.SaveChanges(); if (result > 0) { return new RepositoryActionResult<Schedule>(e, RepositoryActionStatus.Updated); } else { return new RepositoryActionResult<Schedule>(e, RepositoryActionStatus.NothingModified, null); } } catch (Exception ex) { return new RepositoryActionResult<Schedule>(null, RepositoryActionStatus.Error, ex); } }
public RepositoryActionResult<Schedule> InsertSchedule(Schedule e) { try { _ctx.Schedules.Add(e); var result = _ctx.SaveChanges(); if (result > 0) { return new RepositoryActionResult<Schedule>(e, RepositoryActionStatus.Created); } else { return new RepositoryActionResult<Schedule>(e, RepositoryActionStatus.NothingModified, null); } } catch (Exception ex) { return new RepositoryActionResult<Schedule>(null, RepositoryActionStatus.Error, ex); } }
public async Task<IHttpActionResult> Post(string conferenceSlug) { string name = ClaimsPrincipal.Current?.FindFirst("name")?.Value; if (string.IsNullOrWhiteSpace(name)) { return Unauthorized(); } var schedule = await _scheduleRepository.GetSchedules(name) .Include(s => s.Conference) .SingleOrDefaultAsync(s => s.Conference.Slug == conferenceSlug); if (schedule == null) { var conference = await _conferenceRepository.GetConferences().SingleOrDefaultAsync(c => c.Slug == conferenceSlug); var user = await _conferenceRepository.GetUsers().SingleOrDefaultAsync(u => u.Name == name); var newSchedule = new Schedule() { Conference = conference, ConferenceId = conference.Id, Created = DateTime.Now, User = user, UserId = user.Id }; var result = _scheduleRepository.InsertSchedule(newSchedule); schedule = result.Entity; } var dto = Mapper.Map<Tekconf.DTO.Schedule>(schedule); return Ok(dto); }