Matt
Matt

Reputation: 1616

Entity Framework6 Code First Many To Many select always null

I have a Many to Many relationship set up such that in my context I have;

protected override void OnModelCreating(DbModelBuilder modelBuilder){

      modelBuilder.Entity<Module>().HasMany(m => m.Questions).WithMany()
          .Map(q =>
            {
                q.ToTable("Modules_And_Questions");
                q.MapLeftKey("ModuleId");
                q.MapRightKey("QuestionId");
            });

      base.OnModelCreating(modelBuilder);
  }

  public virtual DbSet<Module> Modules { get; set; }
  public virtual DbSet<Question> Questions { get; set; }

executing

_context.Modules.Where(m => m.ModuleId == 3); 

will return me the appropriate module, but the questions element is null. (Checking this in the database shows that there are 40 questions for module 3.)

A breakpoint shows that OnModelCreating is being hit. Though if it helps, I have noticed that mis-spelling any of the elements in quotes within the model builder does not cause an error, so I have my doubts that I am calling / setting this up correctly.

So why is Questions Null, when it should contain a list of 40 Question elements?

Upvotes: 0

Views: 94

Answers (2)

Slauma
Slauma

Reputation: 177163

It does not happen on its own. You must tell EF that you want to load the questions by using Include:

_context.Modules.Include(m => m.Questions).Where(m => m.ModuleId == 3);

If the Module.Questions property is marked as virtual (see Kaf's example) it should work as well. The questions will be loaded as soon as you access the Module.Questions property. However, this will be a second database query while when using Include the questions will be queried together with the modules in a single database request.

Upvotes: 1

Kaf
Kaf

Reputation: 33839

Have you added Question as a collection to the Module class? Try this

public class Medule
{

    //Constructor   
    public Medule()
    {
        Questions = new HashSet<Question>();
    }

    //List of Module properties
    public ModuleId {get; set;}


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

}

Upvotes: 1

Related Questions