0

I'm modelling a simple ASP.NET MVC 5 application for learning purposes.

A user should be able ask and answer questions (A user can only give one answer to a question). How should this be done?

User 1 --> * Answer * --> 1 Question

Because this is my first time modelling with this framework I'm not sure if everything is efficient and if I make good user of the [] statements, should I make adjustments?

User:

public class User
{
    [Key]
    public int UserID { get; set; }
    ...

    public virtual ICollection<Question> Questions { get; set; }
    public virtual ICollection<Answer> Answers{ get; set; }
}

Question:

public class Question
{
    [Key]
    public int QuestionID { get; set; }

    [Required]
    public int UserID { get; set; }

    ....
}

Answer:

public class Answer
{
    [Key]
    public int AnswerID{ get; set; }

    [Required]
    public int UserID { get; set; }
    [Required]
    public int QuestionID { get; set; }

    public virtual User User { get; set; }
    public virtual Question Question { get; set; }
}
1
  • 1
    Question class should have public virtual ICollection<Answer> Answers{ get; set; }. Commented Nov 14, 2014 at 12:50

2 Answers 2

3

Here is a good example for this.

You should use Index attribute with the same name. Such as

 public class Question
       {
       [Index("IX_QuestionAndUser", 1, IsUnique = true)]
        public int QuestionID { get; set; }

        [Index("IX_QuestionAndUser", 1, IsUnique = true)]
        public int UserID { get; set; }

       }
Sign up to request clarification or add additional context in comments.

Comments

1

As you will be going with Entity framework. Following are the useful resources for relation ship in code first models.

Relations in Entity framework

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.