Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying Many to Many and Conditional Where

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.

like image 347
Mike Avatar asked May 29 '12 17:05

Mike


1 Answers

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();
like image 76
Slauma Avatar answered Sep 24 '22 01:09

Slauma