如何使用count在Linq to EF连接的四个表之间获取数据?

时间:2018-12-25 11:32:44

标签: .net sql-server entity-framework linq join

我正在尝试使用Linq到Ef来获取数据我是Linq的新手,

我有桌子

*region having region_id , region_name
*governorate having governorate_id,governorate_name, region_id
*Student having id,governorate_id
*Teachers having id,governorate_id

我想使用一个linq to EF查询来查找每个地区的学生和教师人数

我尝试像只对学生那样在sql查询中完成

select R.region_id,R.region_name , count(IR.Id) as Individual from region R 
inner join governorate G
           on r.region_id=g.region_id
inner join Student IR
            on g.governorate_id=IR.governorate_id
group by R.region_id,R.region_name

希望您的建议

2 个答案:

答案 0 :(得分:0)

要在一个查询中对学生和教师进行计数:

var teachersStudents =
    (
        from r in db.Region
        join g in db.Governorate on r.region_id equals g.region_id
        join s in db.Student on g.governorate_id equals s.governorate_id
        join t in db.Teacher on g.governorate_id equals t.governorate_id
        group new { r, s, t } by new { r.region_id, r.region_name }
        into grp
        select new
        {
            grp.Key.region_id,
            grp.Key.region_name,
            CountStudents = grp.Select(s => s.s.id).Distinct().Count(),
            CountTeachers = grp.Select(t => t.t.id).Distinct().Count()
        }
    ).ToList();

答案 1 :(得分:0)

由于您还使用了Ef,因此我建议您正确设置实体之间的关系,因此您无需自己构建连接查询(并使用Include子句)。

例如:

public class Region
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<Governorate> Governorates { get; set; }
}

public class Governorate
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int RegionId { get; set; }
    public Region Region { get; set; }

    public ICollection<Student> Students { get; set; }
}

public class Student
{
    public int Id { get; set; }

    public int GovernorateId { get; set; }
    public Governorate Governorate { get; set; }
}

希望它对您有帮助,

使用可能对您有帮助的查询进行更新:

var result = whatever.Regions
            .Include(r => r.Governorates)
            .ThenInclude(g => g.Students)
            .GroupBy(r => new {r.Id, r.Name})
            .Select(g => new
            {
                g.Key.Id,
                g.Key.Name,
                Individual = g.Count(r => r.Id)
            }).ToList();

致谢