使用LINQ查询获取学生及其关联班级信息的技术需求
LINQ查询实现学生与关联班级的JSON输出
Got it, let's tackle this problem step by step. You need to write a LINQ query that joins three tables (Student, Classes, and StudentClasses) and outputs the exact JSON structure you provided. Here's how to do it:
首先,确认实体类定义(对应数据库表)
首先我们得有和数据库表对应的实体类,这样LINQ才能正常工作:
// 对应student表 public class Student { public string Code { get; set; } // 对应JSON里的"code"字段 public string Name { get; set; } } // 对应classes表 public class Class { public int Id { get; set; } // 对应JSON里的"id" public string Name { get; set; } // 对应JSON里的"name" } // 对应studentclasses关联表 public class StudentClass { public string StudentId { get; set; } // 外键,关联Student的Code public int ClassId { get; set; } // 外键,关联Class的Id }
LINQ查询与JSON序列化
接下来是核心的LINQ查询,这里假设你用的是Entity Framework(如果是内存集合,逻辑完全一致,只是数据源换成List):
using System.Linq; using System.Text.Json; // 假设你的DbContext实例是dbContext var targetStudent = dbContext.Students // 筛选出你要的学生Lola .Where(student => student.Name == "Lola") // 投影成目标结构 .Select(student => new { code = student.Code, Name = student.Name, classes = dbContext.StudentClasses // 找到该学生的所有关联记录 .Where(sc => sc.StudentId == student.Code) // 关联classes表获取班级详情 .Join(dbContext.Classes, studentClass => studentClass.ClassId, @class => @class.Id, (sc, c) => new { id = c.Id, name = c.Name }) .ToList() }) // 取唯一结果(因为学生姓名应该唯一) .FirstOrDefault(); // 序列化为你需要的JSON格式 var jsonOutput = JsonSerializer.Serialize(targetStudent);
结果说明
这段代码会生成完全符合你要求的JSON:
{"code": "10001", "Name": "Lola", "classes": [ {"id": 1, "name": "class1"}, {"id": 2, "name": "class2"}, {"id": 3, "name": "class3"} ]}
如果你的数据库里Student的主键不是Code而是其他字段(比如Id),只需要把StudentId关联的字段改成对应的主键即可,逻辑是通用的。
内容的提问来源于stack exchange,提问作者Nermine Boulos
相关产品推荐
相关产品推荐

