我有这段代码需要重复很多次(dt_Areas
并且dt_Locations
是DataTable
对象):
ForeignKeyConstraint fkC =
new ForeignKeyConstraint(dt_Areas.Columns["Id"],
dt_Locations.Columns["AreaId"]);
fkC.DeleteRule = Rule.None;
fkC.UpdateRule = Rule.None;
在所有情况下,myDeleteRule
和UpdateRule
必须相同。
所以我想,让我们寻找一个包含规则定义的构造函数,这导致我得到了这段代码:
dt_Locations.Constraints.Add(
new ForeignKeyConstraint("Location_Areas",
"Areas",
"",
new string[]{ "AreaId" },
new string[] {"Id" },
AcceptRejectRule.None,
Rule.None,
Rule.None));
NullReferenceException
由于引用了属性,这不起作用Constraints
,所以让我们解决这个问题:
dt_Locations.Constraints = new ConstraintCollection();
...
但这似乎是不允许的,从这个构建结果可以看出:
error CS0200: Property or indexer 'DataTable.Constraints' cannot be assigned to --
it is read only
首先,我不明白这是从哪里来的:按下F12将我带到这段代码:
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[ResCategoryAttribute("DataCategory_Data")]
[ResDescriptionAttribute("DataTableConstraintsDescr")]
public ConstraintCollection Constraints { get; }
该属性是公共的,并且前几行中的开关不显示“只读”(至少不是我理解的)。
所以我的问题是:由于我有很多表要覆盖,我如何在运行时添加约束,最好使用单行?