I have 2 entity classes with a many-to-many relationship class that is not modeled as a weak entity:
public class Foo
{
public Guid Id { get; private set; }
public ICollection<Baz> Bazs { get; private set; }
}
public class Bar
{
public long Id { get; private set; }
}
public class Baz
{
public Guid Id { get; private set; }
public Foo Foo { get; private set; }
public Bar Bar { get; private set; }
// other things
}
My EntityTypeConfigurations
are built like this:
public class FooConfiguration : EntityTypeConfiguration<Foo>
{
HasMany(f => f.Bazs).WithRequired(b => b.Foo).Map(c => c.ToTable("FooBars"));
}
public class BarConfiguration : EntityTypeConfiguration<Bar>
{
//no navigation mapping
}
public class BazConfiguration : EntityTypeConfiguration<Baz>
{
HasRequired(b => b.Foo).WithMany(f => f.Bazs);
HasRequired(b => b.Bar).WithMany();
}
The problem I'm encountering is that when I load a Foo
, the Bar
side of the Baz
relationship doesn't get loaded. I've changed the properties on Baz
to have backing fields and set breakpoints on the setters, and the setter for Foo
gets called, but the setter for Bar
does not. I've also tried making the Bar
property on Baz
virtual to see if this was a case where eager loading was required for some reason. An example of this usage:
var foo = Set<Foo>.Single(f => f.Id == Id);
var barIds = foo.Bazs.Select(b => b.Bar.Id).ToList();
// the projection lambda throws because b.Bar is null
However, if I load the Bar
s explicitly, they do get populated:
var bars = Set<Bar>().ToList();
var foo = Set<Foo>().Single(f => f.Id == Id);
var barIds = foo.Bazs.Select(b => b.Bar.Id).ToList();
// barIds now contains the correct IDs for the associated Bars
My questions, then, are:
- Is the workaround of loading the
Bar
s before loading theFoo
the only way to get my entities populated? - If not, what am I missing?
Additional information
I've tried using an ICollection<Bar>
directly on Foo
, which works for loading the Foo
->Bar
relationship, but because Baz
is not a weak entity this setup fails on SaveChanges()
.
I've tried mapping the collection both ways, but that's apparently not possible either.