public void AddOrUpdate(PersonDTO dto) { Person dbItem = _mapper.Map(dto); if (dbItem.Id == 0) { _repo.Add(dbItem); } _repo.SaveChanges(); dto.Id = dbItem.Id; }
//POST: api/People public HttpResponseMessage Post(PersonDTO personDTO) { if(ModelState.IsValid) { _service.AddOrUpdate(personDTO); } else { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } return Request.CreateResponse(HttpStatusCode.OK, personDTO); }
//Map: Person DBO to a Person DTO public PersonDTO Map(Person person, bool recursive = true) { PersonDTO dto = new PersonDTO(); dto.Id = person.Id; dto.Name = person.Name; dto.Age = person.Age; if (recursive && person.MoviesActedIn != null) { dto.MoviesActedIn = (from m in person.MoviesActedIn select Map(m, false)).ToList(); } if (recursive && person.MoviesDirected != null) { dto.MoviesDirected = (from m in person.MoviesDirected select Map(m, false)).ToList(); } if (recursive && person.MoviesProduced != null) { dto.MoviesProduced = (from m in person.MoviesProduced select Map(m, false)).ToList(); } return dto; }
//Map: Person DTO to Person DBO public Person Map(PersonDTO dto) { Person dbPerson = null; if ((dbPerson = _repo.Find<Person>(dto.Id)) == null) { dbPerson = new Person(); } dbPerson.Name = dto.Name; dbPerson.Age = dto.Age; if (dto.MoviesActedIn != null) { dbPerson.MoviesActedIn = (from m in _repo.Query<Movie>() where dto.MoviesActedIn.Any(movie => movie.Id == m.Id) select m).ToList(); } if (dto.MoviesDirected != null) { dbPerson.MoviesDirected = (from m in _repo.Query<Movie>() where dto.MoviesDirected.Any(movie => movie.Id == m.Id) select m).ToList(); } if (dto.MoviesProduced != null) { dbPerson.MoviesProduced = (from m in _repo.Query<Movie>() where dto.MoviesProduced.Any(movie => movie.Id == m.Id) select m).ToList(); } return dbPerson; }