查询多对多和有条件的地方 [英] Querying Many to Many and Conditional Where

查看:132
本文介绍了查询多对多和有条件的地方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 保护覆盖在我的上下文文件中,我设置了我的位置类和程序类之间的许多关系。 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);
});

}

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



我的想法是查询连接点(M2M)表,然后将其备份到位置表



问题是我没有代表M2M表的类,而不是在我的OnModelCreating方法中。



我可以找到一个如何做到这一点的例子吗?



基本上选择*从位置l加入位置程序lp在l.LocationId = lp.locationid和lp.programid =传入的东西。



谢谢。

解决方案

  var locations = dbContext.Locations 
.Where(l => l.Programs.Any(p => p.ProgramId == whateverWasPassedInId))
.ToList();

或(因为您的主键属性程序):

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


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

这篇关于查询多对多和有条件的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆