Bart K
Bart K

Reputation: 115

Selecting data from a many-to-many relation with Entity Framework

I have a Code First EF setup with a many-to-many relation between two classes, Quiz and Question. They look like this:

public partial class Quiz
{
    public Quiz()
    {
        Questionnaire = new HashSet<Question>();
    }

    [Key]
    public int Id { get; set; }

    [Required]
    public string Naam { get; set; }

    public ICollection<Question> Questionnaire{ get; set; }
}

public partial class Question
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Question()
    {
        Quizzes = new HashSet<Quiz>();
        Answers = new HashSet<Answer>();
    }

    [Key]
    public int Id { get; set; }

    [Column(TypeName = "ntext")]
    [Required]
    public string Content { get; set; }

    public int CategoryId { get; set; }

    public virtual ICollection<Quiz> Quizzes { get; set; }

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

    public virtual Category Category { get; set; }
}

I've confirmed in my database that EF correctly sets up the linking table QuizQuestions, and the seed data seems to fill in properly as well.

Now, the problem. I have a ViewModel class that's trying to read all the quizzes in the database and add the amount of questions linked to each. Problem is, the "Questionnaire" property doesn't get filled, and I can't figure out why. The ViewModel uses the following code:

using (var context = new KwisContext())
        {
            var quizzes = context.Quizzes.ToList().Select(q => new QuizVM(q));
            Quizzes = new ObservableCollection<QuizVM>(quizzes);
        }

And QuizVM looks like this:

public class QuizVM
{
    private Quiz _q;

    public QuizVM(Quiz q)
    {
        _q = q;
    }

    public string Naam
    {
        get { return _q.Naam; }
    }

    public int QuestionCount
    {
        get {
            return _q.Questionnaire.Count;
        }
    }
}

I've compared my code with someone trying to do something similar (it's for college) but it works with his code and not with mine, and I can't for the life of me see the difference in our approach. Is there something that I could've screwed up in Entity Framework that could cause this to fail?

EDIT: I forgot to mention that I've tried the same code but from the other end, namely requesting every Question in the database and counting the amount of Quizzes they belong to. I've written this with identical code to the above, and this actually does work.

Upvotes: 0

Views: 79

Answers (1)

Dongdong
Dongdong

Reputation: 2508

Use Include explicitely to get linked data

context.Quizzes.Include(x=>x.Questionnaire).ThenInclude(x=>x.OthersThatYouNeed)......

Upvotes: 1

Related Questions