public IHttpActionResult Create(ArtistRequestModel artist) { if (!this.ModelState.IsValid) { return BadRequest(this.ModelState); } var country = this.data .Countries .All() .FirstOrDefault(c => c.Name.ToLower() == artist.Country.ToLower()); if(country == null) { country = new Country { Name = artist.Country }; this.data.Countries.Add(country); this.data.Countries.SaveChanges(); } var newArtist = new Artist { Name = artist.Name, DateOfBirth = artist.DateOfBirth }; newArtist.CountryId = country.Id; this.data.Artists.Add(newArtist); this.data.Artists.SaveChanges(); return Ok(artist); }
public IHttpActionResult Update(int id, ArtistRequestModel artist) { if (!this.ModelState.IsValid) { return BadRequest(this.ModelState); } var country = this.data .Countries .All() .FirstOrDefault(c => c.Name.ToLower() == artist.Country.ToLower()); if (country == null) { country = new Country { Name = artist.Country }; this.data.Countries.Add(country); this.data.Countries.SaveChanges(); } var artistFromDatabase = this.data.Artists.All() .FirstOrDefault(a => a.Id == id); if(artistFromDatabase == null) { return BadRequest("Artist not exist - invalid id"); } artistFromDatabase.Name = artist.Name; artistFromDatabase.DateOfBirth = artist.DateOfBirth; artistFromDatabase.CountryId = country.Id; this.data.Artists.SaveChanges(); return Ok(artist); }