如何在EntityDataSource中处理自联接?

时间:2016-04-10 07:40:03

标签: c# sql asp.net entity-framework entity-framework-6

我想知道如何在EntityDataSource中处理自联接。

如果我有这样的查询:

SELECT b.degree_name ,c.degree_name as degree_next
FROM EMPDEGPROM a INNER JOIN  DEGREEWORK b
ON a.degree_code=b.degree_code
INNER JOIN DEGREEWORK c
ON a.next_degree_code =c.degree_code
WHERE a.emp_num=6777

如何将此数据源用作EntityDataSource。?

我尝试这样做,但我无法获得degree_next

<asp:EntityDataSource ID="EmpPromotionsDS" runat="server"
            ConnectionString="name=CTX" DefaultContainerName="CTX" EnableFlattening="False"
            EntitySetName="EMPDEGPROMs" EntityTypeFilter="EMPDEGPROM" Where="it.EMP_NUM =@emp_num"  Include="DEGREEWORK" >
            <WhereParameters>
                <asp:SessionParameter Name="emp_num" SessionField="emp_num" DbType="Int32" />
            </WhereParameters>

2 个答案:

答案 0 :(得分:2)

创建视图。

CREATE VIEW XXX AS
SELECT a.emp_num, b.degree_name ,c.degree_name as degree_next
FROM EMPDEGPROM a INNER JOIN  DEGREEWORK b
ON a.degree_code=b.degree_code
INNER JOIN DEGREEWORK c
ON a.next_degree_code =c.degree_code

EF从视图中读取没有问题。

答案 1 :(得分:1)

  • 如果您只想要只读,则可以删除EntitySetName,EntityTypeFilter,Where和Include属性,然后使用CommandText属性。

  • 如果您想直接使用您的实体,请确保您的导航属性具有自我引用,并在您的包含属性中对其进行精确处理。

<asp:EntityDataSource ID="EmpPromotionsDS" runat="server"
            ConnectionString="name=CTX" 
            DefaultContainerName="CTX" 
            EnableFlattening="False"
            CommandText= SELECT b.degree_name ,c.degree_name as degree_next
                         FROM EMPDEGPROM a INNER JOIN  DEGREEWORK b
                         ON a.degree_code=b.degree_code
                         INNER JOIN DEGREEWORK c
                         ON a.next_degree_code =c.degree_code
                         WHERE a.emp_num=@EmployeeId>
<CommandParameters>
  <asp:ControlParameter Name="EmployeeId" ControlID="EmployeeIdTextBox" Type="Int32"/>
</CommandParameters>