public async Task <IActionResult> Post([FromBody] SkillEditViewModel vm)
        {
            var skillSet = dbContext.Set <Skill>();
            var existing = await skillSet.FirstOrDefaultAsync(s => s.Name == vm.Name);

            if (existing != null)
            {
                ModelState.AddModelError(nameof(SkillEditViewModel.Name), "A skill with the same name already exists.");
            }

            if (ModelState.IsValid)
            {
                var skill = new Skill();
                vm.ApplyTo(skill);

                skillSet.Add(skill);
                await dbContext.SaveChangesAsync();

                return(CreatedAtRoute("GetSkillById", new { id = skill.Id }, new SkillListViewModel(skill)));
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
        public async Task <IActionResult> Post([FromBody] ContactEditViewModel vm)
        {
            if (ModelState.IsValid)
            {
                if (vm.CompanyId.HasValue)
                {
                    var company = await dbContext.Set <Company>().FindAsync(vm.CompanyId.Value);

                    if (company == null)
                    {
                        ModelState.AddModelError(nameof(ContactListViewModel.CompanyId), "Company not found.");
                        return(BadRequest(ModelState));
                    }
                }

                var contact = new Contact();
                vm.ApplyTo(contact);

                dbContext.Set <Contact>().Add(contact);
                await dbContext.SaveChangesAsync();

                return(CreatedAtRoute("GetContactById", new { id = contact.Id }, new ContactListViewModel(contact)));
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
Beispiel #3
0
        public async Task <IActionResult> Post([FromBody] CompanyEditViewModel vm)
        {
            if (ModelState.IsValid)
            {
                var company = new Company();
                vm.ApplyTo(company);

                dbContext.Set <Company>().Add(company);
                await dbContext.SaveChangesAsync();

                return(CreatedAtRoute("GetCompanyById", new { id = company.Id }, new CompanyListViewModel(company)));
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }