Sql 使用 Entity framework 在两个表之间加入 - 尝试绑定来自两个表的 Gridview 数据

Sql Join between two tables using Entity framework - Trying to bind Gridview data from two tables

我有一个 gridview,最初我是从一个 table (Table 1) 绑定数据,这很简单

gvUsers.dataSource = class.getUsers()
gvUsers.databind()

Function getUsers () As List (Of Users)
  Return (From X in Table1 Select x).ToList()
End Function

但是,我的一些数据指向另一个 table 并且 table 之间没有任何关系(没有外键)

Table 1 
  UID   Name    Age     Blood Type   Test Type
  1     Sam       22          2           3        
  2     Jane      23          2           4        

Table 2

ID  Domain    Code  Description
1   Blood Type  A   A
2   Blood Type  B   B
3   Test Type   1   1
4   Test Type   2   2

目前在 gridView 中,我看到血型值为 2,测试类型为 3、4(第二个 table ID),但我应该在 Table 2 中获取代码列值。 我如何加入这两个 tables - 我知道是否有外键,但列名等同于行数据名这一事实让我很难弄清楚!

干杯

试试这个:

select table1.*, table2.* from table1
inner join table2 on table1.Blood Type = table2.id

您可以select两个表中的所需列。

尝试代码

var result = (from p in Table1.AsEnumerable()
                   join Blood in Table2.AsEnumerable() on p.BloodType equals Blood .ID
                   join Test in  Table2.AsEnumerable() on p.TestTyoe equals Test .ID
                   select new With 
                   {
                       uid = p.UID,
                       Name = p.name,
                       Age = p.age,
                       BloodType = Blood.Code,
                       TestType = Test .Code
                   }).ToList();

Sql 查询是:

 select UID ,Name,Age,B.Code as BloodType ,T.Code as TestType From Table1
 inner join Table2 B on Table1.BloodType = B.ID
 inner join Table2 T on Table1.TestType= T.ID

二手Vb然后

Dim result = from p in Table1.AsEnumerable()
                   join Blood in Table2.AsEnumerable() on p.BloodType equals Blood .ID
                   join Test in  Table2.AsEnumerable() on p.TestTyoe equals Test .ID
                   select               
                        p.UID,
                        p.name,
                        p.age,
                        Blood.Code,
                        Test.Code                    

        gvUsers.DataSource = result