0

Trying to learn MVC and im a bit stuck on foreign keys. Trying to make a simple facebook style posting system.

Users, Posts, And Comments.

There can be many Users, Each User Can Have Many Posts To Their Wall by all other users, each post can have many comments.

The Posts To Comments relationship works fine (i presume due to the naming convention). However the users to posts relationship does not seem to work, when trying to add a user i get the error.

The INSERT statement conflicted with the FOREIGN KEY constraint MVC

What am i doing wrong here, could someone point me in the right direction please. (Also i know my DB structure sucks, im just messing about trying to learn MVC here).

USER

namespace Conference.Models
{
    public class User
    {
        public Int32 UserID { get; set; }
        public string Username { get; set; }

        [ForeignKey("PostedToID")]
        public virtual List<Post> Posts { get; set; }
    }
}

POST

public class Post
{
    [Key]
    public Int32 PostID { get; set; }

//to get the name of the user who posted the post
    public Int32 UserID { get; set; }

//to get the wall the post was posted to
    public Int32 PostedToID { get; set; }

    public DateTime PostDateTime { get; set; }

    [Required(ErrorMessage = "{0} Is Required")]
    [Display(Name = "Post Content")]
    public String PostContent { get; set; }

    public virtual List<Comment> Comments { get; set; }


}

}

COMMENT

public class Comment
{
    public Int32 CommentID { get; set; }

//to get the id of the user that posted the comment
    public Int32 UserID { get; set; }

    public Int32 PostID { get; set; }

    public DateTime CommentDateTime { get; set; }

    [Required(ErrorMessage = "{0} Is Required")]
    [Display(Name = "Comment Content")]
    public String CommentContent { get; set; }
}
loveforfire33
  • 1,090
  • 3
  • 25
  • 46

1 Answers1

1

You can always set the FK relation explicitly. Remove ForeignKey attribute for Posts in User class.

// Foreign key to User
[ForeignKey("User")]
public Int32 PostedToID { get; set; }

Read this.

Community
  • 1
  • 1
Prasad Kanaparthi
  • 6,423
  • 4
  • 35
  • 62
  • Thanks for your time. I tried it that way initially and got / get the exception The ForeignKeyAttribute on property 'PostedToID' on type 'Conference.Models.Post' is not valid. The navigation property 'User' was not found on the dependent type 'Conference.Models.Post'. The Name value should be a valid navigation property name. – loveforfire33 Nov 17 '13 at 01:25