0

我有这段代码需要重复很多次(dt_Areas并且dt_LocationsDataTable对象):

ForeignKeyConstraint fkC = 
  new ForeignKeyConstraint(dt_Areas.Columns["Id"],
                           dt_Locations.Columns["AreaId"]);
fkC.DeleteRule = Rule.None;
fkC.UpdateRule = Rule.None;

在所有情况下,myDeleteRuleUpdateRule必须相同。

所以我想,让我们寻找一个包含规则定义的构造函数,这导致我得到了这段代码:

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; }

该属性是公共的,并且前几行中的开关不显示“只读”(至少不是我理解的)。

所以我的问题是:由于我有很多表要覆盖,我如何在运行时添加约束,最好使用单行?

4

1 回答 1

0

要将代码转换为单个语句,您只需要一个对象初始化程序

var fkC = 
  new ForeignKeyConstraint(dt_Areas.Columns["Id"],dt_Locations.Columns["AreaId"])
    { 
        DeleteRule = Rule.None, 
        UpdateRule = Rule.None 
    };

...并且这段代码可以将该约束添加到DataTable.Constraints属性中:

dt_Locations.Constraints.Add(
  new ForeignKeyConstraint(dt_Areas.Columns["Id"], 
                           dt_Locations.Columns["AreaId"])
    { DeleteRule = Rule.None, 
      UpdateRule = Rule.None });

(出于可读性原因,这被分成多行,但它可以很容易地写成单行。)

于 2021-08-26T12:26:32.013 回答