【问题标题】:Entity Framework - How to query object based on bridge table values?实体框架 - 如何根据桥表值查询对象?
【发布时间】:2023-03-22 20:00:02
【问题描述】:

首先,关于我的餐桌设置:

Group:
    groupId - int
    groupName - varchar

Schedule:
    scheduleId - int
    scheduleName - varchar

Group_Schedules
    scheduleId - int/fk to Schedule
    groupId - int/fk to Group

我使用的是 EF,在上述场景中,没有创建 EF 实体来表示 Group_Schedules,而是将一个集合添加到 Group 和 Schedule 表中,表示另一端。

我需要获取属于某个时间表的所有组,并将我的返回值设为IQueryable<Group>。即(不,这不起作用,因为 EF 生成桥接表的方式):

var g = from g in context.Groups
        where g.Group_Schedule.scheduleId = 1 // This doesn't work because Group_Schedule is a collection of Schedule
        select g;

有没有一种优雅的方式来获取我需要的数据?

【问题讨论】:

    标签: c#-4.0 entity-framework-4


    【解决方案1】:

    这两个都将返回IQueryable<Group>

    var groups = from g in db.Groups
                 where g.Schedules.Any(s => s.scheduleId == 1)
                 select g;
    
    var groups = (from s in db.Schedules
                  where s.scheduleId == 1
                  select s.Groups).SelectMany(g => g);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多