如何在实体框架中创建复杂的连接查询

时间:2014-06-14 19:30:47

标签: sql sql-server asp.net-mvc entity-framework

我是实体框架的新手,我想在mvc4中的实体框架中创建一个查询 以下是我的两张桌子

我希望输出为

enter image description here

请帮忙。

2 个答案:

答案 0 :(得分:1)

SELECT T1.Column1
      ,T2.Col2  AS Column2
      ,T3.Col2  AS Column3
      ,T4.Col2  AS Column4
FROM TABLE1 T1 
LEFT JOIN Table2 T2   ON T1.Column2 = T2.Col1
LEFT JOIN Table2 T3   ON T1.Column3 = T3.Col1
LEFT JOIN Table2 T4   ON T1.Column4 = T4.Col1

答案 1 :(得分:0)

假设您有2个实体映射到名为Table1Table2的表。

var query = 
        from t1 in entities.Table1
        join t2 in entities.Table2 on t1.column2 equals t2.col1
        join t3 in entities.Table2 on t1.column3 equals t3.col1
        join t4 in entities.Table2 on t1.column4 equals t4.col1          
        select new 
         { 
            column1 = t1.column1,
            col2 = t2.col2,
            COLUMN3 = t3.col2,
            COLUMN4 = t4.col2
         };

        return query.ToList();