我的LINQ to Entities查询出了问题

时间:2012-01-30 09:31:45

标签: linq entity-framework linq-to-entities

我目前有一个LINQ查询:

public List<EventSchool> GetEventSchools(int eventID)
    {
        var eventSchools = db.EventSchools
            .Include("Organisation")
            .Where(e => e.EventID == eventID)
            .ToList();

        foreach (var ev in eventSchools)
        {
            if (db.EventSchoolKeyStages.Where(e => e.EventSchoolID == ev.EventSchoolID).Count() > 0)
            {
                int ks = db.EventSchoolKeyStages
                .Where(e => ev.EventSchoolID == ev.EventSchoolID)
                .Sum(e => e.Males + e.Females);

                ev.StudentNumbers = ks;
            }
        }

        return eventSchools;
    }

当我检查EventSchools时,列表中所有项目的学生编号显示为第一项。

例如,如果列表中有3个项目:

Item 1 - Males = 10, Females = 10
Item 2 - Males = 1, Females = 2
Item 3 - Males = 200, Females = 500

所有项目的StudentNumbers为20,而不是:

Item 1 - 20
Item 2 - 3
Item 3 - 700

不确定我做错了什么?

2 个答案:

答案 0 :(得分:2)

您的查询中有错误:

.Where(e => ev.EventSchoolID == ev.EventSchoolID)

应该是:

Where(e => e.EventSchoolID == ev.EventSchoolID)

答案 1 :(得分:2)

你这里有一个错字:

.Where(e => ev.EventSchoolID == ev.EventSchoolID)

这个lambda永远是真的。我怀疑你的意思

.Where(e => e.EventSchoolID == ev.EventSchoolID)
            ^^^

在指定地点有所不同。