在我的 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");
});
}
我正在创建一个搜索/过滤器表单,用户需要能够通过选择一个程序来过滤位置。
我的想法是查询连接 (M2M) 表,然后将其与位置表连接起来。
问题是,除了在我的 OnModelCreating 方法中,我没有代表 M2M 表的类。
我能得到一个关于如何做到这一点的例子吗?
基本上 select * from location l joinlocationsprograms lp on l.LocationId = lp.locationid 和 lp.programid = 传入的任何内容。
谢谢你。
最佳答案
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();
关于entity-framework-4 - 查询多对多和有条件的 where,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10803840/