Example #1
0
        public IHttpActionResult Post([FromBody] List <CreateDemographicModel> commands)
        {
            if (commands == null || !commands.Any() || !ModelState.IsValid)
            {
                return(this.Error().InvalidParameters());
            }

            if (commands.Any(cmd => cmd is null))
            {
                return(this.Error().InvalidParameters("Demographics cannot be null"));
            }

            if (commands.Select(c => c.ExternalRef).Distinct().Count() != commands.Count)
            {
                return(this.Error().InvalidParameters("ExternalRef must be unique"));
            }

            if (commands.Any(c => String.IsNullOrEmpty(c.ExternalRef)))
            {
                return(this.Error().InvalidParameters("ExternalRef is not set"));
            }

            var externalRefs        = commands.Select(x => x.ExternalRef).ToList();
            var existingDemographic = _demographicRepository.GetByExternalRef(externalRefs);

            var addDemographic = commands.Where(c => existingDemographic.All(ex => ex.ExternalRef != c.ExternalRef));

            _demographicRepository.Add(_mapper.Map <IEnumerable <Demographic> >(addDemographic));

            var updateDemographic = existingDemographic.Select(updated =>
            {
                var changes = commands.First(ex => ex.ExternalRef == updated.ExternalRef);
                _mapper.Map(changes, updated);
                return(updated);
            });

            _demographicRepository.UpdateRange(updateDemographic);

            _demographicRepository.SaveChanges();

            return(Ok());
        }