开发者

Struggling to translate SQL Query to Linq in a Domain Services Class and Entity Data Model

Visual Studio 2008 | Silverlight 3 | SQL Server 2005 | Domain Services Class | Entity Data Model

I have a database table "Students" with columns FirstName, LastName, Semester, ProgramOfStudy, Column etc.......

The goal is to return a Total (number of stude开发者_如何转开发nts grouped by first letter of lastname), based on the first letter of the lastname of all students in a given Semester and Programofstudy.

Here is the SQL which works:

SELECT DISTINCT TOP (100) PERCENT LEFT(lastName, 1) AS 'LastNameStartsWith', COUNT(*) AS 'Total', academicPeriod, programCode
FROM         dbo.UM_Students
GROUP BY LEFT(lastName, 1), academicPeriod, programCode
ORDER BY programCode, academicPeriod, 'LastNameStartsWith'

Here is the LINQ that works in LinqPad:

var query = from c in UM_Students
            where c.AcademicPeriod == 200980 && c.ProgramCode == "BSED-ELED-ED"
            group c by c.LastName[0] into cg
            select new { LastNameStartsWith = cg.Key.ToString(), Total = cg.Count(), AcademicPeriod = 200980, ProgramCode =  "BSED-ELED-ED" };
query.Dump();

I am unsuccessful in translating this to my Domain Services class. The main issue has been getting the return type wrong and dealing with anonymous Types.

Here is my effort so far:

public List<lastLetterCounts> GetAlphaCount(int cycleID, string programCode)
{
    List<lastLetterCounts> query = (from c in db.UM_StudentSet
        where c.academicPeriod == 200980 && c.programCode == "BSED-ELED-ED"
        group c by c.lastName[0] into cg
        select new lastLetterCounts { LastNameStartsWith = cg.Key.ToString(), Total = cg.Count(), academicPeriod = cycleID, programCode = programCode }).ToList();

    return query;
}

public class lastLetterCounts
{
    [Key]
    public string LastNameStartsWith { get; set; }
    public int Total { get; set; }
    public int academicPeriod { get; set; }
    public string programCode { get; set; }
}

The Solution compiles and executes, but does not return any data. I don't know how to debug it as the linq evaluates as one big chunk.

This same problem is being asked here but with a different approach.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜