public IHttpActionResult Create(ArticleDataModel model) { var currentUserID = this.User.Identity.GetUserId(); var category = GetCategory(model); var tags = GetTags(model); var article = new Article { AuthorID = currentUserID, DateCreated = DateTime.Now, Title = model.Title, Content = model.Content, CategoryID = category.ID, 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 Ok(model); }
private Category GetCategory(ArticleDataModel model) { var category = this.data.Categories.All() .FirstOrDefault(c => c.Name == model.Category); if (category == null) { category = new Category { Name = model.Category }; this.data.Categories.Add(category); } return category; }
private HashSet<Tag> GetTags(ArticleDataModel model) { HashSet<Tag> tags = new HashSet<Tag>(); var newTagNames = model.Tags.ToList(); var tagsFromTitle = model.Title.Split(' '); newTagNames.AddRange(tagsFromTitle); foreach (var newTagName in newTagNames) { var tag = this.data.Tags.All() .FirstOrDefault(t => t.Name == newTagName); if (tag == null) { tag = new Tag { Name = newTagName }; this.data.Tags.Add(tag); } tags.Add(tag); } return tags; }