在Lambda中将一个表连接到同一个表中的多个时间

时间:2013-11-24 19:34:22

标签: sql asp.net-mvc join lambda inner-join

我的MVC4应用程序中有一个Student实体和一个City实体,Student表中有3个城市代码:

学生实体:

StudentID | StudentName   | BirthCity | LivingCity | UniversityCity |
1           Christof        01           02            03
...


城市实体:

CityID | CityName | 
01       NewYork
02       Los Angeles
03       Washington
...


我想将学生实体加入城市实体,并根据他们的价值显示3个不同的城市名称,如上所示。我尝试了一些例子,但它们与加入不同的表有关(我需要聚集同一个表3次:城市)。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

我认为使用join并不是一个好主意。见下文:

<强>型号:

public class Student
{
    public Student()
    {
        StudentID = 0;
        StudentName = string.Empty;
        BirthCity = string.Empty;
        LivingCity = string.Empty;
        UniversityCity = string.Empty;
    }

    public Student(int id ,string name, string bName,string lName,string uName)
    {
        StudentID = id;
        StudentName = name;
        BirthCity = bName;
        LivingCity = lName;
        UniversityCity = uName;           
    }

    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public string BirthCity { get; set; }
    public string LivingCity { get; set; }
    public string UniversityCity { get; set; }
}

<强>查询:

 Students.Select (
              s => new  Student()
                 {
                    StudentID = s.StudentID, 
                    StudentName = s.StudentName, 
                    BirthCity = Cities
                       .Where (c => (c.CityID == s.BirthCity))
                       .Select (c => c.CityName)
                       .SingleOrDefault (), 
                    LivingCity = Cities
                       .Where (c => (c.CityID == s.LivingCity))
                       .Select (c => c.CityName)
                       .SingleOrDefault (), 
                    UniversityCity = Cities
                       .Where (c => (c.CityID == s.UniversityCity))
                       .Select (c => c.CityName)
                       .SingleOrDefault ()
                 }
           )

答案 1 :(得分:0)

您可以使用子查询执行此操作。它也可以通过连接来完成。

SELECT StudentId,
    (SELECT CityName FROM City WHERE CityId = s.BirthCity),
    (SELECT CityName FROM City WHERE CityId = s.LivingCity),
    (SELECT CityName FROM City WHERE CityId = s.UniversityCity)
FROM Student s