使用LINQ to SQL vb.net通过关联查询表

时间:2016-06-10 01:58:43

标签: vb.net linq-to-sql

我有3张桌子

CustNameTbl

_________________
| ID | CustName |
| 1  | Jel Farm |
| 2  | TSL. TRD.|
| 3  | YAZAKI   |
| 4  | TAILIN   |

ItemNameTbl

_________________
| ID | ItemName |
| 1  |    HSC   |
| 2  |    Pad   |
| 3  |Partition |
| 4  | B002001  |
| 5  |Box for B3|
| 6  |High Speed|

ItemInfoTbl

__________________________________________________
| ID | CustId | ItemId |  Qty  | Price | Remarks |
| 1  |   1    |   1    |   50  |   2   |         |
| 2  |   1    |   2    |  200  |   1   |  Set A  |
| 3  |   1    |   3    |   10  |   5   |  Set B  |
| 4  |   4    |   5    |   15  |   2   |         |
| 5  |   4    |   6    |   10  |   1   |         |
| 6  |   2    |   4    |  150  |   3   |         |

我有两个协会

  1. CustNameTbl as Parent ItemInfoTbl as Child

  2. ItemNameTbl as Parent ItemInfoTbl as Child

  3. 使用Linq to Sql,如何使用CustNameTbl作为WHERE CLAUSE查询ItemInfoTbl,并且其结果是ItemInfoTbl中的CustId和ItemId的值将获取另一个表中的数据(CustNameTbl,ItemNameTbl)

    喜欢这个:

    ____________________________________________________
    | ID | CustId |  ItemId  |  Qty  | Price | Remarks |
    | 4  | TAILIN |Box for B3|   15  |   2   |         |
    | 5  | TAILIN |High Speed|   10  |   1   |         |
    

    但是我的代码没有得到我想要的东西

    Dim CustName As String = "TAILIN"
    Using CustItem As New CustItemDataContext
            Dim resultCustItem = From result In CustItem.ItemInfoTbls
                                 Where result.CustNameTbl.CustName = CustName
            DataGridView1.DataSource = resultCustItem
    End Using
    

    让我开始的任何想法或链接。谢谢你,对不起我的英语。

1 个答案:

答案 0 :(得分:0)

没有测试,但可以给你一个想法。

Dim result = from t in  YourDatabase.ItemInfoTbl
                        join p in YourDatabase.ItemNameTbl on t.ItemID equals p.ID 
                        join c in YourDatabase.CustNameTbl on t.CustID  equals c.ID            
Where c.CustName = CustName
                        select new
                        {
                            t.ID,
                            t.CustId,
                            t.ItemID,
                            t.Qty,
                            t.Price
                         };

有用的来源 LINQ join multi table