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

您必须查询关系,而不是直接设置实体。如果直接查询实体集,则必须手动加入。 –