The request of many for many and conditional

In my context file, I have established many, many relationships between my Location class and the 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 create a search / filter form where the user will need to be able to filter locations by selecting a program.

My thought was to query the connection table (M2M), and then join this backup with the location table.

The problem is that I do not have a class representing the M2M table other than the OnModelCreating method.

Can I get an example on how to do this?

Basically select * from locations l connect the places of the lp program to l.LocationId = lp.locationid and lp.programid = everything that was transferred.

Thank.

+5
source share
1
var locations = dbContext.Locations
    .Where(l => l.Programs.Any(p => p.ProgramId == whateverWasPassedInId))
    .ToList();

(, Program):

var locations = dbContext.Programs
    .Where(p => p.ProgramId == whateverWasPassedInId)
    .Select(p => p.Locations)
    .SingleOrDefault();
+5

All Articles