LINQ Join查询仅返回第二表列,如何获取含所有列的对象列表?
联表查询返回包含多表属性的对象列表解决方案
你当前的查询最后select entry只取了School表的对象,所以自然只能得到School列表。要获取包含Student和School各列属性的对象,你可以用以下两种方式实现:
1. 使用匿名类型(快速实现,适合临时场景)
直接在select语句中定义需要的属性,映射到Student和School的对应列:
var list = (from student in context.Student join school in context.School on student.idSchool equals school.idSchool select new { // 自定义属性名,对应Student表的列 StudentId = student.idStudent, StudentName = student.Name, // 自定义属性名,对应School表的列 SchoolId = school.idSchool, SchoolName = school.SchoolName // 按需添加其他需要的列 }).ToList();
返回的列表中每个对象都会包含你指定的所有属性,属性名可以根据需求自定义,和列名一一对应。
2. 使用自定义DTO类(适合复用场景)
如果需要在多个业务逻辑中使用这个组合对象,建议定义一个专门的数据传输对象(DTO):
// 定义DTO类,属性对应需要的列 public class StudentSchoolInfo { public int StudentId { get; set; } public string StudentName { get; set; } public int SchoolId { get; set; } public string SchoolName { get; set; } // 可添加更多需要的属性 }
然后在查询中实例化这个类并赋值:
var list = (from student in context.Student join school in context.School on student.idSchool equals school.idSchool select new StudentSchoolInfo { StudentId = student.idStudent, StudentName = student.Name, SchoolId = school.idSchool, SchoolName = school.SchoolName }).ToList();
这样得到的是List<StudentSchoolInfo>,类型明确,便于后续维护和复用。
补充:利用EF导航属性简化查询(EF Core适用)
如果你的Student实体已经配置了School的导航属性(比如public School School { get; set; }),可以不用显式写join,直接通过Include加载关联数据,再选择需要的属性:
var list = context.Student .Include(student => student.School) // 加载关联的School数据 .Select(student => new StudentSchoolInfo { StudentId = student.idStudent, StudentName = student.Name, SchoolId = student.School.idSchool, SchoolName = student.School.SchoolName }).ToList();
这种方式更符合Entity Framework的设计习惯,代码更简洁。
内容的提问来源于stack exchange,提问作者Alessandro
相关产品推荐
相关产品推荐

