entity-framework-4 - 查询多对多和有条件的 where

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

        }

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

我的想法是查询连接 (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/

相关文章:

entity-framework-4 - 如何使用存储过程返回 Entity Framework 4 中的单个实体?

sql - 如何在 Entity Framework 查询中连接字符串?

c# - 使用字节作为主键数据类型

entity-framework - 将复杂类型转换为实体而不丢失数据

entity-framework - EF 4.1 Code First 中的 XML 数据类型

c# - 检索 Entity Framework 中的存储过程输出参数始终为空

sql - 我应该在什么情况下使用 Entity SQL?

c# - 我的模型项目中使用代码优先属性来定义模型是否需要 EntityFramework?

c# - 使用原始 SQL 预加载实体

entity-framework - Entity Framework 迁移停止检测POCO更新