I’m trying to make a simple forum using MVC and I can’t figure out why the user that is posting the reply is getting duplicated.
Here is the Reply Action:
[HttpPost]
public ActionResult Reply(string Title, string Content,int ReplyTo)
{
Post masterPost = db.Posts.FirstOrDefault(p => p.PostID == ReplyTo);
Post post = new Post();
post.PostID = 0;
post.CreatedOn = DateTime.Now;
post.ModifiedOn = DateTime.Now;
post.ReplyTo = masterPost;
post.Forum = db.Forums.FirstOrDefault(f=>f.ForumID == masterPost.Forum.ForumID);
post.User = (User)Session["User"];
post.Title = Title;
post.Content = Content;
//if (ModelState.IsValid)
//{
db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("View", "Posts", new { id = ReplyTo });
//}
return View(post);
}
This is the Post entity:
public class Post
{
[Key]
public int PostID { get; set; }
public string Title { get; set; }
[DataType(DataType.MultilineText)]
public string Content { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime? ModifiedOn { get; set; }
public virtual Forum Forum { get; set; }
public virtual User User { get; set; }
public virtual Post ReplyTo { get; set; }
}
This is the User entity:
public class User
{
public int UserID { get; set; }
public string Name { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public DateTime RegisteredOn { get; set; }
}
Whenever the ReplyTo action is called it creates the Post but it also duplicates the User that is stored in the session (with a different UserID).
What am I doing wrong?
Even though you don’t state it, it looks like you use Entity Framework.
If so, the culprit is probably this line
The “User” you store in session is now disconnected from Entity Framework, so EF assumes it is a brand-new user.
There are several ways to solve this. The one I prefer is to also add a UserId property to your Post class and use that
Then do:
Entity Framework uses a convention to understand that you want to link that user to that post.