예제 #1
0
        public async Task <CarDto> Handle(UpdateCarCommand request, CancellationToken cancellationToken)
        {
            var car = await context.Cars.FirstOrDefaultAsync(c => c.PublicId == request.Id, cancellationToken);

            if (car == null)
            {
                throw new CarNotFoundException(request.Id);
            }

            mapper.Map(request, car);
            context.Cars.Update(car);

            try
            {
                await context.SaveChangesAsync(cancellationToken);
            }
            catch (DbUpdateException)
            {
                var makeModelExists = await context.Cars
                                      .AnyAsync(c => c.PublicId != request.Id && c.Make == request.Make && c.Model == request.Model && c.Power == request.Power, cancellationToken);

                if (makeModelExists)
                {
                    throw new CarExistsException(request.Make, request.Model, request.Power);
                }

                throw;
            }

            return(mapper.Map <CarDto>(car));
        }
예제 #2
0
        public async Task <CarDto> Handle(CreateCarCommand request, CancellationToken cancellationToken)
        {
            var car = mapper.Map <Car>(request);

            context.Cars.Add(car);

            try
            {
                await context.SaveChangesAsync(cancellationToken);
            }
            catch (DbUpdateException)
            {
                var carExists = await context.Cars
                                .AnyAsync(c => c.Make == request.Make && c.Model == request.Model && c.Power == request.Power, cancellationToken);

                if (carExists)
                {
                    throw new CarExistsException(request.Make, request.Model, request.Power);
                }

                throw;
            }

            return(mapper.Map <CarDto>(car));
        }
예제 #3
0
        public async Task <Unit> Handle(DeleteCarCommand request, CancellationToken cancellationToken)
        {
            var car = await context.Cars.FirstOrDefaultAsync(c => c.PublicId == request.Id, cancellationToken);

            if (car != null)
            {
                context.Cars.Remove(car);
                await context.SaveChangesAsync(cancellationToken);
            }

            return(Unit.Value);
        }