EnforceConstraint on Datatable

自作多情 提交于 2020-01-04 11:14:11

问题


On a dataset is a EnforceConstraints property indicating whether the constraints should be enabled. Althought a datatable also can have constraints i cannot disable the constraints for a datatable.

My case is that I have datatable which i use in memory with a uniqueconstraint on one of the columns. Sometimes i want to temporarily disable the unique constraint. How can I do this? The only thing I came up with is removing and re-adding the constraint. Is there a better way?


回答1:


There is no public EnforceConstraints property on DataTable. I propose one of the following methods to disable constraints:

  • To temporarily disable constraints use method DataTable.BeginLoadData() and then DataTable.EndLoadData() to reenable them again.
  • Add that DataTable to a (dummy) DataSet and set property DataSet.EnforceConstraints to false.

Note: Disabling checking constraints also disables checking values regarding DataColumn.AllowDBNull and DataColumn.MaxLength.




回答2:


My solution is this

using (IDataReader reader = ExecuteReader(sql))
            {
                DataTable dt = new DataTable();
                using (DataSet ds = new DataSet() { EnforceConstraints = false })
                {
                    ds.Tables.Add(dt);
                    dt.Load(reader, LoadOption.OverwriteChanges);
                    ds.Tables.Remove(dt);
                }
                return dt;
            }



回答3:


Basically what i did is loop through the contrains and remove them. Do the action and re-add the constraints on the table




回答4:


You can use constraints to enforce restrictions on the data in a DataTable, in order to maintain the integrity of the data. Constraints are enforced when the System.Data.DataSet.EnforceConstraints property of the DataSet is true.

There are two kinds of constraints in ADO.NET: the ForeignKeyConstraint and the UniqueConstraint. By default, both constraints are created automatically when you create a relationship between two or more tables by adding a DataRelation to the DataSet. However, you can disable this behavior by specifying createConstraints = fals when creating the relation.




回答5:


If there is data in the datatable when you load it, an exception may be thrown. To play safe, clear your datatable before loading it like this:

MyDataTable.Clear();
MyDataTable.Load(MyDataReader, LoadOption.OverwriteChanges);

This worked for me :)



来源:https://stackoverflow.com/questions/6439709/enforceconstraint-on-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!