删除项目后重定向总是返回null



我正在使用ASP。NET MVC为论坛构建应用程序。我有一个名为Posts的实体和一个名称为PostReplies的实体。

在特定的Post上,将有一个由我的PostReplies实体中的FKPost_Id链接的回复列表。

当我删除帖子上的回复并致电:

RedirectToAction(GetPost, Post, new { id = post.id});

(获取个人帖子,上面有回复列表(

我收到一个与这段代码有关的错误:

var replies = post.Replies;

(帖子,总是返回null(

我不知道为什么,当我添加回复然后重定向回帖子时,它总是重定向得很好。

当我调用delete方法时,我觉得我做了一些根本错误的事情。我将扩展下面的逻辑:

Post实体:

public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime Created { get; set; }
public virtual Discussion Discussion { get; set; }
public virtual ICollection<PostReply> Replies { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}

PostReply实体:

public class PostReply
{
public int Id { get; set; }
public string Content { get; set; }
public DateTime Created { get; set; }
public virtual Post Post { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}

ReplyController-删除回复:

[HttpGet]
public ActionResult DeleteReply(int id)
{
return View(_replyService.GetReply(id));
}
[HttpPost]
public ActionResult DeleteReply(int id, PostReply reply, Post posts)
{
var replies = _replyService.GetReply(id);
_replyService.DeleteReply(id, reply, posts);
return RedirectToAction("GetPost", "Post", new { id = posts.Id });
}

_replyService逻辑(在上面的控制器中调用(:

public void DeleteReply(int id, PostReply reply, Post posts)
{
var replytoDelete = _context.Replies
.FirstOrDefault(r => r.Id == id);
if (replytoDelete != null)
{
_context.Replies.Remove(replytoDelete);
_context.SaveChanges();
}
}

PostController-获取个人帖子:

public ActionResult GetPost(int id)
{
Post post = _postService.GetPost(id);
var replies = post.Replies;
var listofReplies = replies.Select(reply => new NewPostReplyModel
{
Id = reply.Id,
ReplyPosted = reply.Created,
ReplyContent = reply.Content,
ReplyUserId = reply.ApplicationUser.Id,
ReplyUserName = reply.ApplicationUser.UserName
});
var model = new GetPostViewModel
{
Replies = listofReplies,
Posts = BuildNewPost(post)
};
return View(model);
// return View("GetPost", post);
}
private NewPostModel BuildNewPost(Post post)
{
return new NewPostModel
{
PostId = post.Id,
PostContent = post.Content,
PostTitle = post.Title,
DatePosted = post.Created.ToString(),
DiscussionName = post.Discussion.Title,
DiscussionId = post.Discussion.Id,
UserId = post.ApplicationUser.Id,
UserName = post.ApplicationUser.UserName,
};
}

服务中的GetReply逻辑:

public PostReply GetReply(int id)
{
return _context.Replies.Find(id);
}

我认为您的GetPost()方法中没有包含replies,因此,请检查您的代码是否如下:

public Post GetPost(int id)
{
return _context.Posts.Include(p=>p.Replies).FirstOrDefault(p=>p.Id == id);
}

最新更新