1

我從這兩個表使用LINQ到實體獲取數據,主要foriegn密鑰基礎上的表之間存在的關係,結果集即將到來,但每行重複多次reult,但在Db沒有重複的行。不明白如何解決這個問題。ASP.net實體框架行返回重複

這裏是一段代碼:

StringBuilder sb = new StringBuilder(); 
     string text = txtBoxSearch.Text; 
     OLSContainer ols = new OLSContainer(); 
     var result = from tex in ols.COURSEs 
        from another in ols.UNITs 
        where tex.courseName.Contains(text) || tex.description.Contains(text) || another.unitName.Contains(text) 
        select new { tex,another }; 

     foreach (var cours in result) 
     { 
      sb.AppendLine("<h2 id='" + cours.tex.courseID + "'><a href='admin.aspx?id='" + cours.tex.courseID + "''>" + cours.tex.courseName + "</a></h2>"); 
     } 

     foreach (var cours in result) 
     { 
      sb.AppendLine("<h2 id='" + cours.another.unitID + "'><a href='admin.aspx?id='" + cours.another.unitID + "''>" + cours.another.unitName + "</a></h2>"); 
     } 
+0

SQL查詢在探查器中的外觀如何?另外,課程和單元之間的完整關係是什麼?這是一對多嗎? – IronMan84

回答

1

問題是這樣的:

var result = from tex in ols.COURSEs 
      from another in ols.UNITs 

這是一個交叉連接。它將每個課程與每個單元相匹配。它不使用任何FK/PK,因爲在此查詢中沒有使用關係(導航屬性)。要使用該關係,您必須將其修改爲:

var result = from tex in ols.COURSEs 
      from another in tex.SomeNavigationProperty // tex 
+0

如何解決這個問題的解決方法是什麼..我在EDM中有PK,FK關係。 –

+0

您必須查詢關係,而不是直接設置實體。如果直接查詢實體集,則必須手動加入。 –