[英]How do I set a constraint for unique values in a C#.NET dataset table column?
I have one dataset with a few tables. 我有一个带有几个表的数据集。 In one of the tables where I'm adding to, I would like to have a constraint where it will only allow to add a row if I have a unique value in a column. 在我要添加的表之一中,我希望有一个约束,其中仅当我在列中具有唯一值时才允许添加行。
Table: Users Columns: AutoID, GroupID, UnitID*, etc. 表:用户列:AutoID,GroupID,UnitID *等
In the MVS2008, I went to the Designer and set the Unique property for UnitID to true
, but it didn't work. 在MVS2008中,我进入了Designer,并将UnitID的Unique属性设置为true
,但是它不起作用。
I've also hard-coded where I add a row to: this.dataset.Users.UnitIDColumn.Unique = true
and tried a try/catch(InvalidConstraintException), but whenever I hard-code it in, I always get an exception even if the value is unique or not 我还对在其中添加行的位置进行了硬编码: this.dataset.Users.UnitIDColumn.Unique = true
并尝试了try / catch(InvalidConstraintException),但是每当我进行硬编码时,我总是会得到一个异常,甚至如果值是唯一的
How do I limit only adding a row with a unique UnitID? 如何限制仅添加具有唯一UnitID的行? Thanks in advance. 提前致谢。
Per MSDN 每个MSDN
private void AddConstraint(DataTable table)
{
UniqueConstraint uniqueConstraint;
// Assuming a column named "UniqueColumn" exists, and
// its Unique property is true.
uniqueConstraint = new UniqueConstraint(
table.Columns["UniqueColumn"]);
table.Constraints.Add(uniqueConstraint);
}
I believe you can achieve that by designating a column as primary key in the DataSet designer. 我相信您可以通过在DataSet设计器中将一列指定为主键来实现。
I have tried in the DataSet designer to add a DataTable called Test with 2 columns, one of them is called ID which is a primary key. 我曾在DataSet设计器中尝试过添加带有2列的称为Test的DataTable,其中之一称为ID,这是主键。 Just select it, right click and select "Set as Primary Key" 只需选择它,右键单击并选择“设置为主键”
When I tried the following code 当我尝试以下代码时
PharmacyDataSet.TestDataTable table = new PharmacyDataSet.TestDataTable();
table.AddTestRow(1, "one");
table.AddTestRow(1, "oneagain");
I got System.Data.ConstraintException {"Column 'ID' is constrained to be unique. Value '1' is already present."}
我得到了System.Data.ConstraintException {“列'ID'被限制为唯一。值'1'已经存在。”}
The code generated by the designer is 设计人员生成的代码是
this.Constraints.Add(new global::System.Data.UniqueConstraint("Constraint1", new global::System.Data.DataColumn[] {this.columnID}, true)); this.columnID.Unique = true;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.