提问人:Dominique 提问时间:8/26/2021 更新时间:8/26/2021 访问量:40
ForeinKeyConstraint 构造函数有单行代码吗?
Is there a oneliner for ForeinKeyConstraint constructor?
问:
我有这段代码,我需要重复很多次(并且是对象):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;
在所有情况下,my 和 必须相同。DeleteRule
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; }
该属性是公共的,前面几行中的开关不显示“只读”(至少我不明白)。
所以我的问题是:由于我有相当多的表要涵盖,我如何在运行时添加约束,最好使用单行代码?
答:
0赞
Sweeper
8/26/2021
#1
要将该代码转换为单个语句,您只需要一个对象初始值设定项:
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 });
(出于可读性的原因,它被分成多行,但它可以很容易地写成单行。
评论
new ForeignKeyConstraint(dt_Areas.Columns["Id"], dt_Locations.Columns["AreaId"]) { DeleteRule = Rule.None, UpdateRule = Rule.None }