public void TagPost(int postId, string tag) { if (string.IsNullOrEmpty(tag)) { throw new ArgumentException("Tag name is invalid"); } var post = _postRepository.AsQuery().FirstOrDefault(p => p.Id == postId); if (post == null) { throw new ArgumentException(string.Format("Specified post (id={0}) does not exist", postId)); } var tagEntity = _tagRepository.AsQuery().FirstOrDefault(t => t.Name == tag); // check if a given post is already tagged with tag specified if (tagEntity == null || !post.Tags.Any(pt => pt.Id == tagEntity.Id)) { if (tagEntity == null) { tagEntity = new Repositories.Entities.Tag { Name = tag }; _tagRepository.Add(tagEntity); } post.Tags.Add(tagEntity); } }