实体框架使用linq返回连接表

时间:2013-06-26 14:09:54

标签: c# sql linq entity-framework

我有一些表格:

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

谁知道怎么做?感谢

此致

2 个答案:

答案 0 :(得分: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 }

答案 1 :(得分: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
                   };