简体   繁体   中英

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.

In the MVS2008, I went to the Designer and set the Unique property for UnitID to true , but it didn't work.

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

How do I limit only adding a row with a unique UnitID? Thanks in advance.

Per 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.

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. 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."}

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; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM