Querying Many to Many and Conditional Where

限于喜欢 提交于 2020-01-12 07:54:16

问题


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.


回答1:


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();


来源:https://stackoverflow.com/questions/10803840/querying-many-to-many-and-conditional-where

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!