Within my Context file, I set up a many to many relationship between my Location class and Program class.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Location>()
.HasMany(u => u.Programs)
.WithMany(r => r.Locations)
.Map(m =>
{
m.ToTable("LocationsPrograms");
m.MapLeftKey("LocationId");
m.MapRightKey("ProgramId");
});
}
I'm creating a search/filter form where the user will need to be able to filter the locations by selecting a program.
My thought was to query the junction (M2M) table and then join that back up with the locations table.
The problem is that I don't have a class representing the M2M table other than in my OnModelCreating method.
Can I get an example on how to do this?
Basically select * from locations l join locationsprograms lp on l.LocationId = lp.locationid and lp.programid = whatever was passed in.
Thank you.
var locations = dbContext.Locations
.Where(l => l.Programs.Any(p => p.ProgramId == whateverWasPassedInId))
.ToList();
Or (works because your are filtering by the primary key property of Program
):
var locations = dbContext.Programs
.Where(p => p.ProgramId == whateverWasPassedInId)
.Select(p => p.Locations)
.SingleOrDefault();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With