public IHttpActionResult Create(ArticleViewModel model) { if (string.IsNullOrWhiteSpace(model.Title)) { return this.BadRequest("Article title cannot be null or empty!"); } var userID = this.User.Identity.GetUserId(); var tags = GetTags(model); var category = GetOrCreateCategory(model.Category); var article = new Article { Title = model.Title, Content = model.Content, DateCreated = DateTime.Now, CategoryId = category.Id, AuthorId = userID, Tags = tags, }; this.data.Articles.Add(article); this.data.SaveChanges(); model.Id = article.Id; model.DateCreated = article.DateCreated; model.Tags = article.Tags.Select(t => t.Name); return this.CreatedAtRoute("DefaultApi", new { id = model.Id }, model); }
private ICollection<Tag> GetTags(ArticleViewModel article) { if (string.IsNullOrWhiteSpace(article.Title)) { throw new ArgumentNullException("Article title cannot be null or empty!"); } var titleTags = article.Title.Split(' '); var allTags = new HashSet<string>(titleTags); // Check if .Tags is not null foreach (var tag in article.Tags) { allTags.Add(tag); } var articleTags = new HashSet<Tag>(); foreach (var tagName in allTags) { var tag = this.data.Tags.All().FirstOrDefault(t => t.Name == tagName); if (tag == null) { tag = new Tag { Name = tagName }; this.data.Tags.Add(tag); } articleTags.Add(tag); } return articleTags; }