You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linq多对多查询困境求助:GroupJoin与SelectMany用法疑问

嘿,我懂你卡在多对多Linq查询的那种头疼感!先把你的实体类整理成清晰的格式,再给你几个常用的查询示例,应该能帮到你:

你的实体类定义

Course类

public class Course : BaseEntity {
    public Course() {
        CourseCollections = new HashSet<CourseCollection>();
    }
    public int Id { get; set; }
    public string Name { get; set; }
    public int CompanyId { get; set; }
    public virtual ICollection<CourseCollection> CourseCollections { get; set; }
}

CourseCollection类(根据多对多关联的常规结构补充完整)

public class CourseCollection : BaseEntity {
    public int CourseId { get; set; }
    public virtual Course Course { get; set; }
    // 假设关联的集合类为Collection,你可以根据实际业务替换类名
    public int CollectionId { get; set; }
    public virtual Collection Collection { get; set; }
}

实用Linq查询示例

1. 查询指定课程关联的所有集合

var targetCourseId = 1;
var courseWithCollections = dbContext.Courses
    .Include(c => c.CourseCollections)
    .ThenInclude(cc => cc.Collection) // 关联查询集合信息
    .FirstOrDefault(c => c.Id == targetCourseId);

// 遍历输出关联的集合名称
foreach (var relation in courseWithCollections.CourseCollections)
{
    Console.WriteLine(relation.Collection.Name);
}

2. 查询指定集合下某公司的所有课程

var targetCollectionId = 2;
var targetCompanyId = 5;
var filteredCourses = dbContext.CourseCollections
    .Include(cc => cc.Course)
    .Where(cc => cc.CollectionId == targetCollectionId && cc.Course.CompanyId == targetCompanyId)
    .Select(cc => cc.Course)
    .ToList();

3. 查询未关联任何集合的课程

var coursesWithoutCollections = dbContext.Courses
    .Where(c => !c.CourseCollections.Any())
    .ToList();

如果你的实际业务需求和上面的示例不匹配,或者CourseCollection的结构和我补充的不一样,随时说细节,我再帮你调整!

内容的提问来源于stack exchange,提问作者Flimzy_Programmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:13:34