public IHttpActionResult Create(ArticleModel model) { var tags = GetTags(model); var category = GetCategory(model.Category); var userId = this.User.Identity.GetUserId(); var newArticle = new Article { Title = model.Title, Content = model.Content, CategoryId = category.Id, DateCreated = DateTime.Now, AuthorId = userId, Tags = tags }; this.data.Articles.Add(newArticle); this.data.SaveChanges(); model.Id = newArticle.Id; model.DateCreated = newArticle.DateCreated; model.Tags = newArticle.Tags.AsQueryable().Select(TagModel.FromTag).ToArray(); return Ok(model); }
private ICollection<Tag> GetTags(ArticleModel model) { var titleTags = model.Title.Split(' '); var allTags = new HashSet<string>(titleTags); foreach (var modelTag in model.Tags) { allTags.Add(modelTag.Name); } 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; }