簡體   English   中英

Linq-to-Sql聯接如何執行?

[英]How to do this Linq-to-Sql join?

請不要在蘭巴島給我幫助

I have two tables. 
Employees:   
pk           
name        

ExpenseTeamMembers: 
pk                        
expMgrPk
empPk

Example: pk      expMgrPk     empPk     
     1         7          81
     2         7          101
     3         13         99
     4         13         22
     5         13         56

基本上,第一個表是員工列表,第二個表是用於跟蹤哪些員工屬於哪個經理的表。

第一個sql查找有效,mgr在組合框中為我獲取所選名稱的pk。

我要在聯接中執行的操作是查找expMgrPk,並查看屬於該雇員的雇員並返回其姓名而不是其pk。 我很忙,需要一些幫助。 再次請不要在蘭巴島給我幫助! 謝謝

    private void cboManagers_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (cboManagers != null)
        {
            string selectedMgr = (string)cboManagers.SelectedValue;

            using (DataClasses1DataContext db = new DataClasses1DataContext())
            {
                int mgr = (from f in db.employees
                          where f.name == selectedMgr
                          select f.pk).FirstOrDefault();

                var emps = (from m in db.employees
                            join t in db.expenseTeamMembers on m.pk equals t.pK
                            where t.expMgrPk == mgr
                            select m.name).ToList();
                lstSelected.DataSource = emps;
            }
        }
    }

在linq-to-sql中,通過將兩個from語句與where語句結合使用,可以更輕松地編寫聯接。 像這樣:

var emps = (from f in db.employees
            from m in db.expenseTeamMembers
            where m.pk == mgr && f.pk == m.empPk
            select f.name).ToList();

我發現此語法更容易,並且在編譯代碼時,查詢將轉換為傳統的T-SQL連接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM