LINQ:联接 5 或 6 个表并按 1 个表分组,然后按数据分组

本文关键字:然后 数据 联接 LINQ | 更新日期: 2023-09-27 18:32:47

表是: 从子级别到父级别:

TRAINING_TEACHER>教师>学院>街道>区 区域(分区)


我需要显示学院名称,并且是参加分区培训组的男女教师。我的视图模型是:

 public class TRAINING_STATUS_VIEW_MODEL
  {
    public int countMale { get; set; }
    public int countFemale { get; set; }
    public ZONE ZONE_VIEW_MODEL { get; set; }
    public DISTRICT DISTRICT_VIEW_MODEL { get; set; }
    public SUBDISTRICTUPAZILA_VIEW_MODEL { get; set; }
    public INSTITUTE INSTITUTE_VIEW_MODEL { get; set; }
  }

其中countMale,countFemale是每个学院根据性别划分TRAINING_TEACHER教师人数。教师表中有一个性别列。现在这是我无法按研究所和计数执行分组的查询。

var trainingStatusReport = 
from trainingTeacher in db.TRAINING_TEACHER 
join teacher in db.TEACHERs on trainingTeacher.TEACHER_NO equals teacher.TABLE_ID 
join institute in db.INSTITUTEs on teacher.INS_ID equals institute.INS_ID
join subDistrict in db.subDistricts on institute.LOC_ID equals (decimal)subDistrict.LOC_ID
join district in db.DISTRICTs on (decimal)subDistrict.DCODE equals (decimal)district.DCODE
join zone  in db.ZONEs on  district.ZC equals  zone.ZC   
select new TRAINING_STATUS_VIEW_MODEL { 
..........
.......... I can't go here
} ;

我已经尝试过institute.ins_id组研究所,但无法在选择部分编码。

LINQ:联接 5 或 6 个表并按 1 个表分组,然后按数据分组

可以使用

具有进一步联接的组,但效率可能低下。联接的更好替代方法是

  1. 使用导航属性
  2. 使用 let 语句可以简化任何其他复杂逻辑。

下面是如何将两者结合起来的示例。这能解决问题吗?

var trainingStatusReport =
    from trainingTeacher in db.TRAINING_TEACHER
    group trainingTeacher by trainingTeacher.Teacher.Institute into instituteGroup
    let institute = instituteGroup.Select(t => t.Teacher.Institute).FirstOrDefault()
    select new TRAINING_STATUS_VIEW_MODEL
    {
        countMale = instituteGroup.Count(t => t.Teacher.Gender == Male),
        countFemail = instituteGroup.Count(t => t.Teacher.Gender == Femail),
        ZONE = institute.SubDistrict.District.Zone,
        DISTRICT = institute.SubDistrict.District,
        SUBDISTRICT = institute.SubDistrict,
        INSTITUTE = institute
    };
相关文章: