// DELETE: api/Default/5 public IHttpActionResult Delete(int id, NewSnippetViewModel snippetViewModel) { using (var context = new AspectKnowledgebaseContext()) { var snippet = context.Snippets .Where(s => s.Id == id) .FirstOrDefault(); context.Entry(snippet).State = System.Data.Entity.EntityState.Deleted; context.SaveChanges(); } return(Ok()); }
public int Post(NewSnippetViewModel snippetViewModel) { using (var context = new AspectKnowledgebaseContext()) { var snippet = new Snippet() { Code = snippetViewModel.Code, Subject = snippetViewModel.Subject }; foreach (var tag in snippetViewModel.Tags) { var foundTag = context.Tags.FirstOrDefault(t => t.Id == tag.Id); if (foundTag != null) { snippet.Tags.Add(foundTag); } else { var newTag = new Tag() { Name = tag.Name }; context.Tags.Add(newTag); snippet.Tags.Add(newTag); } } context.Snippets.Add(snippet); context.SaveChanges(); return(snippet.Id); } }
// PUT: api/Default/5 public IHttpActionResult Put(SnippetViewModel snippet) { if (!ModelState.IsValid) { return(BadRequest("Not a valid model")); } using (var context = new AspectKnowledgebaseContext()) { // Linq var existingSnippet = context.Snippets.Where(s => s.Id == snippet.Id) .FirstOrDefault <Snippet>(); if (existingSnippet != null) { existingSnippet.Code = snippet.Code; existingSnippet.Subject = snippet.Subject; //existingSnippet.Tags = snippet; } else { return(NotFound()); } var newTags = snippet.Tags; var existingTags = existingSnippet.Tags.ToList(); foreach (var tag in existingTags) { var doesTagAlreadyExist = newTags.Any(o => o.Id == tag.Id); if (!doesTagAlreadyExist) { existingSnippet.Tags.Remove(tag); } } foreach (var tag in newTags) { var doesTagAlreadyExist = existingTags.Any(o => o.Id == tag.Id); if (!doesTagAlreadyExist) { var foundTag = context.Tags.FirstOrDefault(t => t.Id == tag.Id); if (foundTag != null) { existingSnippet.Tags.Add(foundTag); } else { var newTag = new Tag() { Name = tag.Name }; context.Tags.Add(newTag); existingSnippet.Tags.Add(newTag); } } } context.Entry(existingSnippet).State = System.Data.Entity.EntityState.Modified; context.SaveChanges(); } return(Ok()); }