2013-06-26 30 views
-4

我有一些表:实体框架使用LINQ返回连接表

table1: 
id1 
fk_tb2 // this is the fk to table2 

table2: 
id2 
fk_tb3 //this is the fk to table3 

table3: 
id3 
name3 

现在我想返回一个表,如: ID1 fk_tb2 NAME3

有谁知道如何做到这一点?由于

问候,

+0

阅读此篇:http://stackoverflow.com/questions/10750146/linq-select-to-new-object –

回答

6

加入表和使用匿名类型返回所需的字段:

from t1 in table1 
join t2 in table2 on t1.fk_tb2 equals t2.id2 
join t3 in table3 on t2.fk_tb3 equals t3.id3 
select new { t1.id1, t2.id2, t3.name3 } 
+0

感谢,这将是返回类型?因为我需要将它写入返回此函数的函数中。 – Leona

+0

匿名类型将是匿名的:)你不能从方法返回匿名对象。如果你想返回这三个值,那么创建一些类'public class Foo {public int Id1 {get;组; } ...这将有三个属性Id1,Id2,Name。而返回此类的实例,而不是:'选择新的Foo {ID1 = t1.id1,Id2的= t2.id2,名称= t3.name3}' –

0

如果您在导航以及映射,你可以这样做

var m = from tb1 in dbContext.table1 
     select new { 
        id1 = tb1.id1, 
        fk_tb2 = tb1.table2.tb2, 
        name3 = tb1.table2.table3.name3 
        }; 

其他你可以做

var m = from tb1 in dbContext.table1 
     join tb2 in dbContext.table2 on tb2.id2 equals tb1.fk_tb2 
     join tb3 in dbContext.table3 on tb3.id3 equals tb2.fk_tb3 
     select new { 
        id1 = tb1.id1, 
        fk_tb2 = tb2.id2, 
        name3 = tb3.name3 
        };