0

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?

2 Answers 2

1

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.

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

2 Comments

If I use the syntax you propose I get an error, "Cannot Convert Lambda expression to type 'string'". However using Include("Questions") works. So should your syntax work and I am missing somethign?
@Matt: For the lambda version of Include you must add using System.Data.Entity; to your code file.
1

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; } } 

1 Comment

I hadn't instantiated the collection in the constructor, though I had the property. That means that I no longer have a null collection of questions, but it still doesnt populate.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.