EnforceConstraint on Datatable

Gluip picture Gluip · Jun 22, 2011 · Viewed 11.9k times · Source

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?

Answer

Fernando Diaz Toledano picture Fernando Diaz Toledano · Oct 30, 2015

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