且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

“无法启用此约束,因为并非所有值都有对应的父值."

更新时间:2023-02-04 10:06:36

无法启用此约束,因为并非所有值都有对应的父值.

This constraint cannot be enabled as not all values have corresponding parent values.

您在此处为父表新建了一行:

You made a new row for the parent table here:

DataRow row = tableObj2.NewRow();

但是您似乎没有将其添加到父表中.我希望在尝试向引用此新行的子表中添加行之前,在某处看到这样的代码:

But you don't seem to have added it to the parent table. I would expect to see code like this somewhere before you attempt to add rows to a child table that references this new row:

tableObj2.Rows.Add(row);

因为您从未添加过此行,所以直到告诉数据集这些表相关的那一刻,您的代码才一直成功,此时它说子表中的一个或多个行在其中没有对应的父行"父表"

Because you never added this row your code succeeds all the way up to the moment you tell the DataSet these tables are related at which point it says "one or more rows in your child table don't have a corresponding parent row in the parent table"

记住;调用NewRow会给您一个新的Detached行.它必须添加到表中才能作为关系的一部分

Remember; calling NewRow gives you a new Detached row. It has to be added to a table to function as part of a relationship

在其他新闻中,如果右键单击您的项目,添加一个新项目,类别Data,键入DataSet,则您的生活会好很多.打开DataSet,右键单击设计图面,选择Add .. Datatable.通过右键单击并选择add..column来指定列.通过单击父ID中列名旁边行的灰色部分来指定您的关系,以使整个行变为蓝色,然后将蓝色行拖到另一个数据表中的子ID上并将其拖放.这将创建一个类型化的数据集.它们在智能感知中使用起来要好得多,因为它们为列等输入了属性,因此,此 row ["ID"] = 1 var x =(int)row ["ID"] -该行的ID属性为整数,因此它是 row.ID = 1 var x = row.ID -强类型,而不是字符串:)

In other news, your life will get a lot nicer if you right click your project, add a new item, category Data, type DataSet.. open the DataSet, right click the design surface, choose Add.. Datatable. Specify your columns by right clicking it and choosing add..column. Specify your relation by clicking the grey part of the row next to the column name in the parent ID so that the whole row goes blue then dragging the blue row onto the child id in the other datatable and dropping it. This makes a typed DataSet. They're a lot nicer to work with in intellisense because they have typed properties for columns etc so none of this row["ID"] = 1 or var x = (int)row["ID"] - the row will have an ID property that is integer so it's row.ID = 1 or var x = row.ID - strongly typed, not stringly typed :)

如果要创建强类型的数据集,请记住以下简单规则:如果访问.Rows或.Columns集合(或将列名放入字符串中),则可能做错了.这些集合返回基本的DataRow/DataColumn对象,这些对象将您带回到字符串类型的世界

If you do make a strongly typed DataSet remember this simple rule: if you're accessing the .Rows or .Columns collections (or putting a column name in a string) you're probably doing it wrong. These collections return base DataRow/DataColumn objects, which put you back in stringly typed world

//no
dt.Rows[0]

//yes
dt[0]

//no
dt.Columns["Colname"]

//yes
dt.ColnameColumn

//no
dt[0].IsNull("Colname")

//yes
dt[0].IsColnameNull()