Linq和带有整数键的外键Lookup表

时间:2012-10-17 15:48:40

标签: linq

我有一个表格所在的数据库:

Table1:
Table1Id int

Table2:
Table2Id int
ForeignKeyToTable1 int

LookupTable:
Table2Id
Table3Id

Table3:
Table3Id int
Table3Field varchar

我想:

select table1.* from table1
inner join table2 on table1.Table1Id = ForeignKeyToTable1 
inner join LookupTable on LookupTable.Table2Id = table2.Table2Id 
inner join Table3 on table3.Table3Id = LookupTable.Table3Id
where table3.Table3Field ='qwerty'

如何在Linq中实现这一目标?

2 个答案:

答案 0 :(得分:0)

我相信这样的事情会发生

var query = from t1 in context.Table1
            join t2 in context.Table2 
                 on t1.Table1Id equals t2.ForeignKeyToTable1 
            join lt in context.LookupTable 
                 on t2.Table2Id equals lt.Table2Id
            join t3 in context.Table3 
                 on lt.Table3Id equals t3.Table3Id
            where t3.Table3Field == "qwerty"
            select t1;

答案 1 :(得分:0)

var query = 
            from table1 in db.Table1
            join table2 in db.Table2 on new { Table1Id = table1.Table1Id } equals new { Table1Id = table2.ForeignKeyToTable1 }
            join lookuptable in db.LookupTable on table2.Table2Id equals lookuptable.Table2Id
            join table3 in db.Table3 on lookuptable.Table3Id equals table3.Table3Id
            where
              table3.Table3Field == "qwerty"
            select new {
              table1.Table1Id
            };