数据集未执行

时间:2012-09-24 17:47:16

标签: c# asp.net database vb.net

<WebMethod(Description:="JSON Hierarchy Object")> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
    Public Function xmlData() As Object

        Using _ds As DataSet = db.ExecuteDataSet(CommandType.Text, "Select NodeID, NodeName,ParentID from Nodes WHERE ParentID=1")
            _ds.DataSetName = "Menus"
            _ds.Tables(0).TableName = "Menu"
            Dim relation As New DataRelation("ParentChild", _ds.Tables("Menu").Columns("NodeID"), _ds.Tables("Menu").Columns("ParentID"), True)
            relation.Nested = True
            _ds.Relations.Add(relation)
            Dim StrDc As String() = New String(_ds.Tables(0).Columns.Count - 1) {}
            Dim HeadStr As String = String.Empty
            For i As Integer = 0 To _ds.Tables(0).Columns.Count - 1
                StrDc(i) = _ds.Tables(0).Columns(i).Caption
                HeadStr += """" + StrDc(i) + """ : """ + StrDc(i) + i.ToString() + "¾" + ""","
            Next
            HeadStr = HeadStr.Substring(0, HeadStr.Length - 1)
            Dim Sb As New StringBuilder()
            Sb.Append("{""" + _ds.Tables(0).TableName + """ : [")
            For i As Integer = 0 To _ds.Tables(0).Rows.Count - 1
                Dim TempStr As String = HeadStr
                Sb.Append("{")
                For j As Integer = 0 To _ds.Tables(0).Columns.Count - 1
                    TempStr = TempStr.Replace(_ds.Tables(0).Columns(j).ToString + j.ToString() + "¾", _ds.Tables(0).Rows(i)(j).ToString())
                Next
                Sb.Append(TempStr + "},")
            Next
            Sb = New StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1))
            Sb.Append("]}")
            Return Sb.ToString
        End Using

    End Function

我使用上面的函数返回JSON String但是当我在这个sql查询ParentID=1中使用Select NodeID, NodeName,ParentID from Nodes WHERE ParentID=1时,我收到以下错误

System.ArgumentException: This constraint cannot be enabled as not all values have corresponding parent values.
   at System.Data.ConstraintCollection.AddForeignKeyConstraint(ForeignKeyConstraint constraint)
   at System.Data.ConstraintCollection.Add(Constraint constraint, Boolean addUniqueWhenAddingForeign)
   at System.Data.DataRelationCollection.DataSetRelationCollection.AddCore(DataRelation relation)
   at System.Data.DataRelationCollection.Add(DataRelation relation)
   at Haggler.xmlData() in D:\2008VS\Haggler\EntLib5\App_Code\Haggler.vb:line 114

表格结构:

enter image description here

当我从Sql Query中删除Where子句时,它工作正常。非常感谢非常感谢。

1 个答案:

答案 0 :(得分:2)

您可以使用此代码替换(Replace True with False)

Dim relation As New DataRelation("ParentChild", _ds.Tables("Menu").Columns("NodeID"), _ds.Tables("Menu").Columns("ParentID"), False)

链接:http://msdn.microsoft.com/fr-fr/library/9ae5a582%28v=vs.80%29.aspx