示例#1
0
        public async Task <Data.Vehicle> AddOrUpdateVehicleAsync(VehicleViewModel model)
        {
            if (model == null)
            {
                throw new NullReferenceException("VehicleViewModel is null");
            }

            Data.Vehicle entity = null;

            var existing = await _context.Vehicle
                           .Include(x => x.VehicleExtension)
                           .Include(x => x.VehicleOwner)
                           .Where(x => x.RegistrationNumber.ToLower() == model.RegistrationNumber.ToLower() &&
                                  x.VehicleExtension != null &&
                                  x.VehicleExtension.Deactivated == false)
                           .ToListAsync();

            if (!existing.Any())
            {
                entity    = model.ToEntity();
                entity.Id = 0;
                entity.VehicleExtension.VehicleId = entity.Id;
                await _context.Vehicle.AddAsync(entity);
            }
            else
            {
                foreach (Data.Vehicle item in existing)
                {
                    item.VehicleExtension.Deactivated = true;
                    _context.VehicleOwner.RemoveRange(item.VehicleOwner);
                    _context.VehicleUser.RemoveRange(item.VehicleUser);
                }

                existing[0].UpdateEntity(model);
                existing[0].VehicleExtension.Deactivated = false;
                existing[0].VehicleExtension.UpdatedAt   = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc);
                existing[0].VehicleExtension.RequestId   = model.ExtensionRequestId;

                _context.Vehicle.Update(existing[0]);
                entity = existing[0];
            }


            await _context.SaveChangesAsync();

            return(entity);
        }