LINQ to SQL连接两个表,根据子表中的两个不同列选择父表两次

时间:2010-08-23 06:26:27

标签: c# vb.net linq linq-to-sql

我想在C#和VB.NET中得到建议

我有两个表Employees和CafeLogs。有些员工可以是收银员,也可以是咖啡店的顾客。

表格结构:

  • 员工:EmployeeId(PK),FirstName,LastName
  • CafeLogs:LogId(PK),CashierId,EmployeeId,Value,=> CashierId和EmployeeId是Empoyee表的EmployeeId列中的数据

表关系:

  • 员工1:N CafeLogs(CashierId(FK))

员工表数据:

EmployeeId,FirstName,LastName

  • 1,Steve,Marks
  • 2,路易斯,约翰
  • 3,Scoot,Joe
  • 4,Steven,Gerald
  • 5,布朗,雷克萨斯

    CafeLogs表数据:

    LogId,CashierId,EmployeeId,Value

    • 1,2,3,9
    • 2,3,4,12
    • 3,2,5,8
    • 4,3,1,4
    • 5,3,1,2
    • 6,2,5,9
    • 7,2,4,1
  

通缉结果:我想从一个查询中显示收银员名称和员工姓名:

  • LogId,员工,收费,价值
  • 1,Scoot Joe,Louis John,9
  • 2,Steven Gerald,Scoot Joe,12
  • 3,Brown Lexus,Louis John,8
  • 4,Steve Marks,Scoot Joe,4
  • 5,Steve Marks,Scoot Joe,2
  • 6,Brown Lexus,Louis John,9
  • 7,Steven Gerald,Lours John,1

    现在我知道如何只选择LogId,员工的姓名和价值,而不选择收银员名称。

     Dim query = From log In db.CafeLogs _
                Join emp In db.Employees On emp.EmployeeId Equals log.EmployeeId _
                Select log.LogId, emp.FirsName, emp.LastName, log.Value
    

1 个答案:

答案 0 :(得分:6)

这应该在C#中执行:

var query = from log in db.CafeLogs
            join emp in db.Employees on log.EmployeeId equals emp.EmployeeId
            join cas in db.Employees on log.CashierId  equals cas.EmployeeId
            select new
            {
                log.LogId,
                Employee  = emp.FirstName + " " + emp.LastName,
                ChargedBy = cas.FirstName + " " + cas.LastName,
                log.Value
            };

和VB版本:

Dim query = From log In db.CafeLogs                                          _
            Join emp In db.Employees On log.EmployeeId Equals emp.EmployeeId _
            Join cas In db.Employees On log.CashierId  Equals cas.EmployeeId _
            Select                                                           _
                log.LogId,                                                   _
                Employee  = emp.FirstName & " " & emp.LastName,              _
                ChargedBy = cas.FirstName & " " & cas.LastName,              _
                log.Value