查询多对多和有条件的地方

Mik*_*ike 6 entity-framework-4 ef-code-first

在我的Context文件中,我在Location类和Program类之间建立了多对多的关系.

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");
            });

        }
Run Code Online (Sandbox Code Playgroud)

我正在创建一个搜索/过滤器表单,用户需要通过选择程序来过滤位置.

我的想法是查询联结(M2M)表,然后将其连接到位置表.

问题是我没有一个代表M2M表的类,而不是我的OnModelCreating方法.

我可以举例说明如何做到这一点吗?

基本上选择*从位置l加入locationsprograms lp on l.LocationId = lp.locationid和lp.programid =传入的任何内容.

谢谢.

Sla*_*uma 7

var locations = dbContext.Locations
    .Where(l => l.Programs.Any(p => p.ProgramId == whateverWasPassedInId))
    .ToList();
Run Code Online (Sandbox Code Playgroud)

或者(因为您按主键属性过滤Program):

var locations = dbContext.Programs
    .Where(p => p.ProgramId == whateverWasPassedInId)
    .Select(p => p.Locations)
    .SingleOrDefault();
Run Code Online (Sandbox Code Playgroud)