public async Task<IActionResult> Add(AddCommentModel model) { if (!ModelState.IsValid) { string message = this.ModelState.Values.Where(t => t.ValidationState == ModelValidationState.Invalid) .Select(t => t.Errors.FirstOrDefault()) .FirstOrDefault() .ErrorMessage; return this.Notice(message); } var result = await this.CommentService.Add(model); if (result.Success) { return this.Redirect(this.GenerateCommentLink(model.TopicID, result.Data)); } else { return this.Notice(result.ErrorMessage); } }
public async Task<Result<long>> Add(AddCommentModel model) { using (var uw = this.CreateUnitOfWork()) { var topic = await uw.GetAsync<Topic>(t => t.ID == model.TopicID && !t.IsDelete); if (topic == null) { return Result<long>.ErrorResult("该主题不存在"); } else if (topic.IsLock) { return Result<long>.ErrorResult("该主题已被锁定"); } if (model.ReplyTo.HasValue) { var replyToComment = await uw.GetAsync<Comment>(t => t.ID == model.ReplyTo.Value && !t.IsDelete); if (replyToComment == null) { return Result<long>.ErrorResult("该评论不存在"); } if (replyToComment.TopicID != model.TopicID) { return Result<long>.ErrorResult("错误的请求"); } } using (var tran = uw.BeginTransaction()) { var entity = new Comment { Content = model.Content, CreateDate = DateTime.Now, CreateUser = this.SecurityManager.CurrentUser.ID, IsDelete = false, ReplyID = model.ReplyTo, TopicID = model.TopicID }; await uw.InsertAsync(entity); topic.LastReplyDate = DateTime.Now; topic.LastReplyUserID = this.SecurityManager.CurrentUser.ID; await uw.UpdateAsync(topic); #region 发送回复主题的消息 { if (this.SecurityManager.CurrentUser.ID != topic.CreateUser) { var addMessageModel = new AddMessageModel { Comment = entity.ID, FromUser = this.SecurityManager.CurrentUser.ID, Topic = topic.ID, ToUser = topic.CreateUser, Type = MessageType.Comment }; await this.MessageService.Add(addMessageModel); } } #endregion #region 发送@的评论 { var atUserList = Utility.AtHelper.FetchUsers(model.Content); if (atUserList.Count > 0) { var userList = await uw.QueryAsync<User>(t => atUserList.Contains(t.UserName)); foreach (var user in userList) { if (user.ID == this.SecurityManager.CurrentUser.ID || user.ID == topic.CreateUser) //过滤@自己,过滤重复@作者 { continue; } var addMessageModel = new AddMessageModel { Comment = entity.ID, FromUser = this.SecurityManager.CurrentUser.ID, Topic = topic.ID, ToUser = user.ID, Type = MessageType.At }; await this.MessageService.Add(addMessageModel); } } } #endregion tran.Commit(); return Result.SuccessResult(entity.ID); } } }