//Activate This Construntor to log All To Standard output //public TestClass():base(true){} //Activate this constructor to log Failures to a log file //public TestClass(System.IO.TextWriter tw):base(tw, false){} //Activate this constructor to log All to a log file //public TestClass(System.IO.TextWriter tw):base(tw, true){} //BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES public void run() { Exception exp = null; DataSet ds = new DataSet(); DataTable dtParent = GHTUtils.DataProvider.CreateParentDataTable(); ds.Tables.Add(dtParent); UniqueConstraint uc1,uc2; uc1 = new UniqueConstraint(dtParent.Columns[0]); uc2 = new UniqueConstraint(dtParent.Columns[1]); try { BeginCase("different columnn"); Compare(uc1.Equals(uc2),false); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} //Two System.Data.ForeignKeyConstraint are equal if they constrain the same columns. try { BeginCase("same column"); uc2 = new UniqueConstraint(dtParent.Columns[0]); Compare(uc1.Equals(uc2),true); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} }
//Activate This Construntor to log All To Standard output //public TestClass():base(true){} //Activate this constructor to log Failures to a log file //public TestClass(System.IO.TextWriter tw):base(tw, false){} //Activate this constructor to log All to a log file //public TestClass(System.IO.TextWriter tw):base(tw, true){} //BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES public void run() { Exception exp = null; DataTable dtParent = GHTUtils.DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint(dtParent.Columns[0]); PropertyCollection pc = uc.ExtendedProperties ; try { base.BeginCase("Checking ExtendedProperties default "); base.Compare(pc != null,true); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { base.BeginCase("Checking ExtendedProperties count "); base.Compare(pc.Count ,0); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} }
//Activate This Construntor to log All To Standard output //public TestClass():base(true){} //Activate this constructor to log Failures to a log file //public TestClass(System.IO.TextWriter tw):base(tw, false){} //Activate this constructor to log All to a log file //public TestClass(System.IO.TextWriter tw):base(tw, true){} //BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES public void run() { Exception exp = null; DataTable dtParent = GHTUtils.DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint(dtParent.Columns[0],false); try { BeginCase("ToString - default"); Compare(uc.ToString(), string.Empty ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} uc = new UniqueConstraint("myConstraint",dtParent.Columns[0],false); try { BeginCase("Tostring - Constraint name"); Compare(uc.ToString(), "myConstraint"); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} }
//Activate This Construntor to log All To Standard output //public TestClass():base(true){} //Activate this constructor to log Failures to a log file //public TestClass(System.IO.TextWriter tw):base(tw, false){} //Activate this constructor to log All to a log file //public TestClass(System.IO.TextWriter tw):base(tw, true){} //BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES public void run() { Exception exp = null; DataTable dtParent = GHTUtils.DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint(dtParent.Columns[0],false); dtParent.Constraints.Add(uc); try { BeginCase("primary key 1"); Compare(uc.IsPrimaryKey , false); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} dtParent.Constraints.Remove(uc); uc = new UniqueConstraint(dtParent.Columns[0],true); dtParent.Constraints.Add(uc); try { BeginCase("primary key 2"); Compare(uc.IsPrimaryKey , true); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} }
//Activate This Construntor to log All To Standard output //public TestClass():base(true){} //Activate this constructor to log Failures to a log file //public TestClass(System.IO.TextWriter tw):base(tw, false){} //Activate this constructor to log All to a log file //public TestClass(System.IO.TextWriter tw):base(tw, true){} //BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES public void run() { Exception exp = null; DataTable dtParent = GHTUtils.DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint(dtParent.Columns[0]); try { BeginCase("Columns 1"); Compare(uc.Columns.Length ,1); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("Columns 2"); Compare(uc.Columns[0],dtParent.Columns[0]); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} }
//Activate This Construntor to log All To Standard output //public TestClass():base(true){} //Activate this constructor to log Failures to a log file //public TestClass(System.IO.TextWriter tw):base(tw, false){} //Activate this constructor to log All to a log file //public TestClass(System.IO.TextWriter tw):base(tw, true){} //BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES public void run() { Exception exp = null; DataTable dtParent = GHTUtils.DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint("myConstraint",new DataColumn[] {dtParent.Columns[0],dtParent.Columns[1]}); try { BeginCase("Ctor"); Compare(uc == null ,false ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("Ctor name"); Compare(uc.ConstraintName ,"myConstraint"); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} }
public void BuildTable() { DataTable table = new DataTable(_table); DataColumnCollection cols = table.Columns; cols.Add(_id, typeof(int)); cols.Add(_OrderNumber, typeof(string)); cols.Add(_ParentId, typeof(int)); cols.Add(_OrderDate, typeof(DateTime)); cols.Add(_EmployeeId, typeof(int)); cols.Add(_CustomerId, typeof(int)); cols.Add(_POSId, typeof(int)); cols.Add(_OrderStateId, typeof(int)); cols.Add(_OrderTypeId, typeof(int)); cols.Add(_ShipDate, typeof(DateTime)); cols.Add(_ShipperId, typeof(int)); cols.Add(_ShipperName, typeof(string)); cols.Add(_ShippingFee, typeof(float)); cols.Add(_CurrencyId, typeof(int)); cols.Add(_CurrencyRate, typeof(int)); cols.Add(_ShippingName, typeof(string)); cols.Add(_ShippingAddress, typeof(string)); cols.Add(_ShippingCity, typeof(string)); cols.Add(_ShippingZipCode, typeof(string)); cols.Add(_ShippingCounttry, typeof(string)); cols.Add(_Phone, typeof(string)); cols.Add(_email, typeof(string)); UniqueConstraint uc = new UniqueConstraint(cols[_id], true); table.Constraints.Add(uc); this.Tables.Add(table); }
//Activate This Construntor to log All To Standard output //public TestClass():base(true){} //Activate this constructor to log Failures to a log file //public TestClass(System.IO.TextWriter tw):base(tw, false){} //Activate this constructor to log All to a log file //public TestClass(System.IO.TextWriter tw):base(tw, true){} //BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES public void run() { Exception exp = null; DataTable dtParent = GHTUtils.DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint(dtParent.Columns[0]); try { BeginCase("default "); Compare(uc.ConstraintName ,string.Empty ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} uc.ConstraintName = "myConstraint"; try { BeginCase("set/get "); Compare(uc.ConstraintName ,"myConstraint" ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} }
public void BuildTable() { DataTable table = new DataTable(_table); DataColumnCollection cols = table.Columns; cols.Add(_Id, typeof(int)); cols.Add(_UserName, typeof(string)); cols.Add(_Password, typeof(string)); cols.Add(_ContactName, typeof(string)); cols.Add(_Company, typeof(string)); cols.Add(_JobTitle, typeof(string)); cols.Add(_BillingAddress, typeof(string)); cols.Add(_BillingCity, typeof(string)); cols.Add(_BillingZipCode, typeof(string)); cols.Add(_BillingCountry, typeof(string)); cols.Add(_ShippingCity, typeof(string)); cols.Add(_ShippingZipCode, typeof(string)); cols.Add(_ShippingCountry, typeof(string)); cols.Add(_MobilePhone, typeof(string)); cols.Add(_OfficePhone, typeof(string)); cols.Add(_HomePhone, typeof(string)); cols.Add(_FaxNumber, typeof(string)); cols.Add(_TaxCode, typeof(string)); cols.Add(_Email1, typeof(string)); cols.Add(_Email2, typeof(string)); cols.Add(_Website, typeof(string)); UniqueConstraint uc = new UniqueConstraint(cols[_Id], true); table.Constraints.Add(uc); this.Tables.Add(table); }
public SqlCommandUniqueValidator( ITablePopulator table, UniqueConstraint unique, string connectionString ) : base(table,unique,new SqlFactory(),connectionString) { }
public UniqueValidatorBase(ITablePopulator table, UniqueConstraint unique) { if(table==null) throw new ArgumentNullException("table"); if(unique==null) throw new ArgumentNullException("unique"); this.table=new WeakReference(table); this.unique=unique; }
//Activate This Construntor to log All To Standard output //public TestClass():base(true){} //Activate this constructor to log Failures to a log file //public TestClass(System.IO.TextWriter tw):base(tw, false){} //Activate this constructor to log All to a log file //public TestClass(System.IO.TextWriter tw):base(tw, true){} //BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES public void run() { Exception exp = null; DataTable dtParent = GHTUtils.DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint("myConstraint",dtParent.Columns[0],false); dtParent.Constraints.Add(uc); try { BeginCase("Ctor"); Compare(uc == null ,false ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("primary key 1"); Compare(dtParent.PrimaryKey.Length ,0); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("Ctor name 1"); Compare(uc.ConstraintName ,"myConstraint"); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} dtParent.Constraints.Remove(uc); uc = new UniqueConstraint("myConstraint",dtParent.Columns[0],true); dtParent.Constraints.Add(uc); try { BeginCase("primary key 2"); Compare(dtParent.PrimaryKey.Length ,1); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("Ctor name 2"); Compare(uc.ConstraintName ,"myConstraint"); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} }
public Constraint Add(string name, DataColumn[] columns, bool primaryKey) { UniqueConstraint constraint = new UniqueConstraint(name, columns); this.Add(constraint); if (primaryKey) { this.Table.PrimaryKey = columns; } return constraint; }
public static DataTable Colores() { DataTable tblColores = datos.Tables[3]; tblColores.TableName = "Colores"; if (!tblColores.Constraints.Contains("descripcionConstraint")) { UniqueConstraint uniqueConstraint = new UniqueConstraint("descripcionConstraint", tblColores.Columns["DescripcionCOL"]); tblColores.Constraints.Add(uniqueConstraint); } return tblColores; }
public static DataTable Clientes() { DataTable tblClientes = datos.Tables[2]; tblClientes.TableName = "Clientes"; if (!tblClientes.Constraints.Contains("idConstraint")) { UniqueConstraint uniqueConstraint = new UniqueConstraint("idConstraint", tblClientes.Columns["CorreoCLI"]); tblClientes.Constraints.Add(uniqueConstraint); } return tblClientes; }
public static DataTable ArticulosItems() { DataTable tblArticulosItems = datos.Tables[1]; tblArticulosItems.TableName = "ArticulosItems"; if (!tblArticulosItems.Constraints.Contains("descripcionConstraint")) { UniqueConstraint uniqueConstraint = new UniqueConstraint("descripcionConstraint", tblArticulosItems.Columns["DescripcionITE"]); tblArticulosItems.Constraints.Add(uniqueConstraint); } return tblArticulosItems; }
public static DataTable Clientes() { DataTable tblClientes = datos.Tables[1]; tblClientes.TableName = "clientes"; if (!tblClientes.Constraints.Contains("descripcionConstraint")) { UniqueConstraint uniqueConstraint = new UniqueConstraint("descripcionConstraint", tblClientes.Columns["CUIT"]); tblClientes.Constraints.Add(uniqueConstraint); } return tblClientes; }
public void BuildTable() { DataTable table = new DataTable(_table); DataColumnCollection cols = table.Columns; cols.Add(_id, typeof(int)); cols.Add(_name, typeof(string)); cols.Add(_logourl, typeof(string)); UniqueConstraint uc = new UniqueConstraint(cols[_id], true); table.Constraints.Add(uc); this.Tables.Add(table); }
protected override void GenerateUnique(System.Data.UniqueConstraint unique) { StringWriter tw = new StringWriter(); tw.WriteLine("ALTER TABLE {0} ADD CONSTRAINT {1} {2} (", formatTableName(unique.Table), unique.ConstraintName, (unique.IsPrimaryKey) ? "PRIMARY KEY" : "UNIQUE" ); GenerateColumnList(tw, unique.Columns); this.Admin.ExecuteNonQuery(ConnectionString, tw.ToString()); }
[Test] public void Columns() { DataTable dtParent = DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint(dtParent.Columns[0]); // Columns 1 Assert.AreEqual(1, uc.Columns.Length , "UC1"); // Columns 2 Assert.AreEqual(dtParent.Columns[0], uc.Columns[0], "UC2"); }
private void button6_Click(object sender, System.EventArgs e) { //创建唯一约束 System.Data.UniqueConstraint ucNew; ucNew = new System.Data.UniqueConstraint("MyUnique", this.dsUntyped.Tables["dtMain"].Columns["MainValue"]); //添加唯一约束 this.dsUntyped.Tables["dtMain"].Constraints.Add(ucNew); string strMessage; strMessage = "新的约束名称为: "; strMessage += this.dsUntyped.Tables["dtMain"].Constraints["MyUnique"].ConstraintName.ToString(); MessageBox.Show(strMessage); }
public DbCommandUniqueValidatorBase( ITablePopulator table, UniqueConstraint unique, IDbFactory dbFactory, string connectionString ) : base(table,unique) { if (dbFactory == null) throw new ArgumentNullException("factory"); if (connectionString == null) throw new ArgumentNullException("connectionString"); this.dbFactory = dbFactory; this.connectionString = connectionString; }
internal void Add(Constraint constraint, bool addUniqueWhenAddingForeign) { if (constraint == null) { throw ExceptionBuilder.ArgumentNull("constraint"); } if (this.FindConstraint(constraint) != null) { throw ExceptionBuilder.DuplicateConstraint(this.FindConstraint(constraint).ConstraintName); } if ((1 < this.table.NestedParentRelations.Length) && !this.AutoGenerated(constraint)) { throw ExceptionBuilder.CantAddConstraintToMultipleNestedTable(this.table.TableName); } if (constraint is UniqueConstraint) { if (((UniqueConstraint) constraint).bPrimaryKey && (this.Table.primaryKey != null)) { throw ExceptionBuilder.AddPrimaryKeyConstraint(); } this.AddUniqueConstraint((UniqueConstraint) constraint); } else if (constraint is ForeignKeyConstraint) { ForeignKeyConstraint constraint2 = (ForeignKeyConstraint) constraint; if (addUniqueWhenAddingForeign && (constraint2.RelatedTable.Constraints.FindKeyConstraint(constraint2.RelatedColumnsReference) == null)) { if (constraint.ConstraintName.Length == 0) { constraint.ConstraintName = this.AssignName(); } else { this.RegisterName(constraint.ConstraintName); } UniqueConstraint constraint3 = new UniqueConstraint(constraint2.RelatedColumnsReference); constraint2.RelatedTable.Constraints.Add(constraint3); } this.AddForeignKeyConstraint((ForeignKeyConstraint) constraint); } this.BaseAdd(constraint); this.ArrayAdd(constraint); this.OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, constraint)); if ((constraint is UniqueConstraint) && ((UniqueConstraint) constraint).bPrimaryKey) { this.Table.PrimaryKey = ((UniqueConstraint) constraint).ColumnsReference; } }
private void BindGrid(IPropertyCollection properties) { this.properties = properties; DataSet ds = new DataSet(); DataTable dt = new DataTable("this"); dt.Columns.Add("this", Type.GetType("System.Object")); ds.Tables.Add(dt); dt.Rows.Add(new object[] { this }); dt = new DataTable("MyData"); DataColumn k = dt.Columns.Add("Key", stringType); k.AllowDBNull = false; DataColumn v = dt.Columns.Add("Value", stringType); v.AllowDBNull = false; ds.Tables.Add(dt); UniqueConstraint pk = new UniqueConstraint(k, false); dt.Constraints.Add(pk); ds.EnforceConstraints = true; this.colKey.HeaderText = "Key"; this.colKey.TextBox.Enabled = true; this.colValue.HeaderText = "Value"; this.colValue.MappingName = "Value"; DataRowCollection rows = dt.Rows; foreach(IProperty prop in properties) { rows.Add(new object[] { prop.Key, prop.Value } ); } this.Grid.DataSource = dt.DefaultView; this.InitializeGrid(); this.colKey.TextBox.BorderStyle = BorderStyle.None; this.colValue.TextBox.BorderStyle = BorderStyle.None; this.colKey.TextBox.Move += new System.EventHandler(this.ColorTextBox); this.colValue.TextBox.Move += new System.EventHandler(this.ColorTextBox); dt.RowChanged += new DataRowChangeEventHandler(PropertyGridRowChanged); dt.RowDeleting += new DataRowChangeEventHandler(PropertyGridRowDeleting); dt.RowDeleted += new DataRowChangeEventHandler(PropertyGridRowDeleted); }
public void BuildTable() { DataTable table = new DataTable(_table); DataColumnCollection cols = table.Columns; cols.Add(_id, typeof(int)); cols.Add(_name, typeof(string)); cols.Add(_brand, typeof(string)); cols.Add(_urlImage, typeof(string)); cols.Add(_sellingPrice, typeof(string)); cols.Add(_warrantyMonth, typeof(string)); cols.Add(_note, typeof(string)); UniqueConstraint uc = new UniqueConstraint(cols[_id], true); table.Constraints.Add(uc); this.Tables.Add(table); }
public static DataTable AlicuotasIva() { DataTable tblAlicuotasIva = datos.Tables[9]; tblAlicuotasIva.TableName = "alicuotasiva"; if (!tblAlicuotasIva.Constraints.Contains("idConstraint")) { UniqueConstraint uniqueConstraint = new UniqueConstraint("idConstraint", tblAlicuotasIva.Columns["IdAlicuotaALI"]); tblAlicuotasIva.Constraints.Add(uniqueConstraint); } if (!tblAlicuotasIva.Constraints.Contains("descripcionConstraint")) { UniqueConstraint uniqueConstraint = new UniqueConstraint("descripcionConstraint", tblAlicuotasIva.Columns["PorcentajeALI"]); tblAlicuotasIva.Constraints.Add(uniqueConstraint); } return tblAlicuotasIva; }
public static DataTable CondicionIva() { DataTable tblCondicionIva = datos.Tables[10]; tblCondicionIva.TableName = "condicioniva"; if (!tblCondicionIva.Constraints.Contains("idConstraint")) { UniqueConstraint uniqueConstraint = new UniqueConstraint("idConstraint", tblCondicionIva.Columns["IdCondicionIvaCIVA"]); tblCondicionIva.Constraints.Add(uniqueConstraint); } if (!tblCondicionIva.Constraints.Contains("descripcionConstraint")) { UniqueConstraint uniqueConstraint = new UniqueConstraint("descripcionConstraint", tblCondicionIva.Columns["DescripcionCIVA"]); tblCondicionIva.Constraints.Add(uniqueConstraint); } return tblCondicionIva; }
//Activate This Construntor to log All To Standard output //public TestClass():base(true){} //Activate this constructor to log Failures to a log file //public TestClass(System.IO.TextWriter tw):base(tw, false){} //Activate this constructor to log All to a log file //public TestClass(System.IO.TextWriter tw):base(tw, true){} //BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES public void run() { Exception exp = null; DataSet ds = new DataSet(); DataTable dtParent = GHTUtils.DataProvider.CreateParentDataTable(); ds.Tables.Add(dtParent); UniqueConstraint uc = null; uc = new UniqueConstraint(dtParent.Columns[0]); try { BeginCase("Table"); Compare(uc.Table ,dtParent ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} }
public static DataTable GetAlicuotasIva() { MySqlConnection SqlConnection1 = DALBase.GetConnection(); MySqlDataAdapter SqlDataAdapter1 = new MySqlDataAdapter(); MySqlCommand SqlSelectCommand1 = new MySqlCommand("AlicuotasIva_Listar", SqlConnection1); SqlDataAdapter1.SelectCommand = SqlSelectCommand1; SqlSelectCommand1.CommandType = CommandType.StoredProcedure; DataTable tbl = new DataTable(); SqlDataAdapter1.Fill(tbl); SqlConnection1.Close(); if (!tbl.Constraints.Contains("descripcionConstraint")) { UniqueConstraint uniqueConstraint = new UniqueConstraint("descripcionConstraint", tbl.Columns["IdAlicuotaALI"]); tbl.Constraints.Add(uniqueConstraint); } return tbl; }
public static DataSet GetClientes(sbyte frm) { MySqlConnection SqlConnection1 = DALBase.GetConnection(); MySqlDataAdapter SqlDataAdapter1 = new MySqlDataAdapter(); MySqlCommand SqlSelectCommand1 = new MySqlCommand("Clientes_Listar", SqlConnection1); SqlSelectCommand1.Parameters.AddWithValue("p_frm", frm); SqlDataAdapter1.SelectCommand = SqlSelectCommand1; SqlSelectCommand1.CommandType = CommandType.StoredProcedure; DataSet dt = new DataSet(); SqlDataAdapter1.Fill(dt, "Clientes"); if (!dt.Tables[0].Constraints.Contains("correoConstraint")) { UniqueConstraint uniqueConstraint = new UniqueConstraint("correoConstraint", dt.Tables[0].Columns["CorreoCLI"]); // dt.Tables[0].Constraints.Add(uniqueConstraint); } SqlConnection1.Close(); return dt; }
[Test] public void IsPrimaryKey() { DataTable dtParent = DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint(dtParent.Columns[0],false); dtParent.Constraints.Add(uc); // primary key 1 Assert.AreEqual(false, uc.IsPrimaryKey , "UC5"); dtParent.Constraints.Remove(uc); uc = new UniqueConstraint(dtParent.Columns[0],true); dtParent.Constraints.Add(uc); // primary key 2 Assert.AreEqual(true, uc.IsPrimaryKey , "UC6"); }
public DbInMemInvestorPosition() { dtInvestorPosition.Columns.Add(InstrumentID, Type.GetType("System.String")); dtInvestorPosition.Columns.Add(PosiDirection, typeof(TThostFtdcPosiDirectionType)); dtInvestorPosition.Columns.Add(HedgeFlag, typeof(TThostFtdcHedgeFlagType)); dtInvestorPosition.Columns.Add(PositionDate, typeof(TThostFtdcPositionDateType)); dtInvestorPosition.Columns.Add(Position, Type.GetType("System.Int32")); //dtInvestorPosition.Columns.Add("TodayPosition", Type.GetType("System.Int32")); //因为PositionDate有了区分,所以TodayPosition可以不专门用字段记录 UniqueConstraint uniqueConstraint = new UniqueConstraint(new DataColumn[] { dtInvestorPosition.Columns[InstrumentID], dtInvestorPosition.Columns[PosiDirection], dtInvestorPosition.Columns[HedgeFlag], dtInvestorPosition.Columns[PositionDate] }); dtInvestorPosition.Constraints.Add(uniqueConstraint); }
public IUniqueValidator this[System.Data.UniqueConstraint unique] { get { return((IUniqueValidator)this.contraints[unique]); } set { if (unique == null) { throw new ArgumentNullException("unique"); } if (value == null) { throw new ArgumentNullException("value"); } this.contraints[unique] = value; } }
private void AddUniqueConstraint(UniqueConstraint constraint) { DataColumn[] columns = constraint.Columns; for (int i = 0; i < columns.Length; i++) { if (columns[i].Table != this.table) { throw ExceptionBuilder.ConstraintForeignTable(); } } constraint.Key.GetSortIndex().AddRef(); if (!constraint.CanEnableConstraint()) { constraint.Key.GetSortIndex().RemoveRef(); throw ExceptionBuilder.UniqueConstraintViolation(); } }
private UniqueConstraint FindUniqueConstraint(ConstraintCollection cl) { UniqueConstraint uc = null; // find if the unique constraint already exists in the parent table. foreach (Constraint o in cl) { if (!(o is UniqueConstraint)) { continue; } uc = (UniqueConstraint)o; //Check in ParentColumns if (CompareDataColumns(ParentColumns, uc.Columns)) { return(uc); } } return(null); }
/// <summary> /// Clears the collection of all rows. /// </summary> public void Clear() { if (this.table.DataSet != null && this.table.DataSet.EnforceConstraints) { foreach (Constraint c in table.Constraints) { UniqueConstraint uc = c as UniqueConstraint; if (uc == null) { continue; } if (uc.ChildConstraint == null || uc.ChildConstraint.Table.Rows.Count == 0) { continue; } string err = String.Format("Cannot clear table Parent because " + "ForeignKeyConstraint {0} enforces Child.", uc.ConstraintName); #if NET_1_1 throw new InvalidConstraintException(err); #else throw new ArgumentException(err); #endif } } #if NET_2_0 table.DataTableClearing(); #endif List.Clear(); // Remove from indexes table.ResetIndexes(); #if NET_2_0 table.DataTableCleared(); #endif OnListChanged(this, new ListChangedEventArgs(ListChangedType.Reset, -1, -1)); }
internal override Constraint Clone(DataSet destination, bool ignorNSforTableLookup) { int index; if (ignorNSforTableLookup) { index = destination.Tables.IndexOf(this.Table.TableName); } else { index = destination.Tables.IndexOf(this.Table.TableName, this.Table.Namespace, false); } if (index < 0) { return(null); } DataTable table = destination.Tables[index]; int length = this.ColumnsReference.Length; DataColumn[] columns = new DataColumn[length]; for (int i = 0; i < length; i++) { DataColumn column = this.ColumnsReference[i]; index = table.Columns.IndexOf(column.ColumnName); if (index < 0) { return(null); } columns[i] = table.Columns[index]; } UniqueConstraint constraint = new UniqueConstraint(this.ConstraintName, columns); foreach (object obj2 in base.ExtendedProperties.Keys) { constraint.ExtendedProperties[obj2] = base.ExtendedProperties[obj2]; } return(constraint); }
internal UniqueConstraint Clone(DataTable table) { int length = this.ColumnsReference.Length; DataColumn[] columns = new DataColumn[length]; for (int i = 0; i < length; i++) { DataColumn column = this.ColumnsReference[i]; int index = table.Columns.IndexOf(column.ColumnName); if (index < 0) { return(null); } columns[i] = table.Columns[index]; } UniqueConstraint constraint = new UniqueConstraint(this.ConstraintName, columns); foreach (object obj2 in base.ExtendedProperties.Keys) { constraint.ExtendedProperties[obj2] = base.ExtendedProperties[obj2]; } return(constraint); }
private void PopulateDefaultSort(UniqueConstraint uc) { if (isInitPhase) { return; } DataColumn [] columns = uc.Columns; if (columns.Length == 0) { sort = String.Empty; return; } StringBuilder builder = new StringBuilder(); builder.Append(columns[0].ColumnName); for (int i = 1; i < columns.Length; i++) { builder.Append(", "); builder.Append(columns [i].ColumnName); } sort = builder.ToString(); }
internal void FinishInitConstraints() { if (this.delayLoadingConstraints != null) { for (int i = 0; i < this.delayLoadingConstraints.Length; i++) { DataColumn[] columnArray; int length; if (this.delayLoadingConstraints[i] is UniqueConstraint) { if (!this.fLoadForeignKeyConstraintsOnly) { UniqueConstraint constraint2 = (UniqueConstraint)this.delayLoadingConstraints[i]; if (constraint2.columnNames == null) { this.Add(constraint2); } else { length = constraint2.columnNames.Length; columnArray = new DataColumn[length]; for (int j = 0; j < length; j++) { columnArray[j] = this.table.Columns[constraint2.columnNames[j]]; } if (constraint2.bPrimaryKey) { if (this.table.primaryKey != null) { throw ExceptionBuilder.AddPrimaryKeyConstraint(); } this.Add(constraint2.ConstraintName, columnArray, true); } else { UniqueConstraint constraint4 = new UniqueConstraint(constraint2.constraintName, columnArray); if (this.FindConstraint(constraint4) == null) { this.Add(constraint4); } } } } } else { ForeignKeyConstraint constraint = (ForeignKeyConstraint)this.delayLoadingConstraints[i]; if ((constraint.parentColumnNames == null) || (constraint.childColumnNames == null)) { this.Add(constraint); } else if (this.table.DataSet == null) { this.fLoadForeignKeyConstraintsOnly = true; } else { length = constraint.parentColumnNames.Length; columnArray = new DataColumn[length]; DataColumn[] childColumns = new DataColumn[length]; for (int k = 0; k < length; k++) { if (constraint.parentTableNamespace == null) { columnArray[k] = this.table.DataSet.Tables[constraint.parentTableName].Columns[constraint.parentColumnNames[k]]; } else { columnArray[k] = this.table.DataSet.Tables[constraint.parentTableName, constraint.parentTableNamespace].Columns[constraint.parentColumnNames[k]]; } childColumns[k] = this.table.Columns[constraint.childColumnNames[k]]; } ForeignKeyConstraint constraint3 = new ForeignKeyConstraint(constraint.constraintName, columnArray, childColumns) { AcceptRejectRule = constraint.acceptRejectRule, DeleteRule = constraint.deleteRule, UpdateRule = constraint.updateRule }; this.Add(constraint3); } } } if (!this.fLoadForeignKeyConstraintsOnly) { this.delayLoadingConstraints = null; } } }
// Add the foriegn keys to the schema. private void AddForeignKeys(DataRelation rel, ArrayList names, bool isConstraintOnly) { // Do nothing if it contains hidden relation foreach (DataColumn col in rel.ParentColumns) { if (col.ColumnMapping == MappingType.Hidden) { return; } } foreach (DataColumn col in rel.ChildColumns) { if (col.ColumnMapping == MappingType.Hidden) { return; } } w.WriteStartElement("xs", "keyref", xmlnsxs); w.WriteAttributeString("name", XmlHelper.Encode(rel.RelationName)); //ForeignKeyConstraint fkConst = rel.ChildKeyConstraint; UniqueConstraint uqConst = null; if (isConstraintOnly) { foreach (Constraint c in rel.ParentTable.Constraints) { uqConst = c as UniqueConstraint; if (uqConst == null) { continue; } if (uqConst.Columns == rel.ParentColumns) { break; } } } else { uqConst = rel.ParentKeyConstraint; } string concatName = XmlHelper.Encode(rel.ParentTable.TableName) + "_" + XmlHelper.Encode(uqConst.ConstraintName); // first try to find the concatenated name. If we didn't find it - use constraint name. if (names.Contains(concatName)) { w.WriteStartAttribute("refer", String.Empty); w.WriteQualifiedName(concatName, dataSetNamespace); w.WriteEndAttribute(); } else { w.WriteStartAttribute("refer", String.Empty); w.WriteQualifiedName(XmlHelper.Encode(uqConst.ConstraintName), dataSetNamespace); w.WriteEndAttribute(); } if (isConstraintOnly) { w.WriteAttributeString(XmlConstants.MsdataPrefix, XmlConstants.ConstraintOnly, XmlConstants.MsdataNamespace, "true"); } else if (rel.Nested) { w.WriteAttributeString( XmlConstants.MsdataPrefix, XmlConstants.IsNested, XmlConstants.MsdataNamespace, "true"); } AddExtendedPropertyAttributes(uqConst.ExtendedProperties); w.WriteStartElement("xs", "selector", xmlnsxs); w.WriteAttributeString("xpath", ".//" + ConstraintPrefix + XmlHelper.Encode(rel.ChildTable.TableName)); w.WriteEndElement(); foreach (DataColumn c in rel.ChildColumns) { w.WriteStartElement("xs", "field", xmlnsxs); w.WriteStartAttribute("xpath", String.Empty); if (c.ColumnMapping == MappingType.Attribute) { w.WriteString("@"); } w.WriteString(ConstraintPrefix); w.WriteString(XmlHelper.Encode(c.ColumnName)); w.WriteEndAttribute(); w.WriteEndElement(); // field } w.WriteEndElement(); // keyref }
// check if a table can be removed from this collectiuon. // if the table can not be remved act according to throwException parameter. // if it is true throws an Exception, else return false. private bool CanRemove(DataTable table, bool throwException) { // check if table is null reference if (table == null) { if (throwException) { throw new ArgumentNullException("table"); } return(false); } // check if the table has the same DataSet as this collection. if (table.DataSet != this.dataSet) { if (!throwException) { return(false); } throw new ArgumentException("Table " + table.TableName + " does not belong to this DataSet."); } // check the table has a relation attached to it. if (table.ParentRelations.Count > 0 || table.ChildRelations.Count > 0) { if (!throwException) { return(false); } throw new ArgumentException("Cannot remove a table that has existing relations. Remove relations first."); } // now we check if any ForeignKeyConstraint is referncing 'table'. foreach (Constraint c in table.Constraints) { UniqueConstraint uc = c as UniqueConstraint; if (uc != null) { if (uc.ChildConstraint == null) { continue; } if (!throwException) { return(false); } RaiseForeignKeyReferenceException(table.TableName, uc.ChildConstraint.ConstraintName); } ForeignKeyConstraint fc = c as ForeignKeyConstraint; if (fc == null) { continue; } if (!throwException) { return(false); } RaiseForeignKeyReferenceException(table.TableName, fc.ConstraintName); } return(true); }
internal void FinishInitConstraints() { if (_delayLoadingConstraints == null) { return; } int colCount; DataColumn[] parents, childs; for (int i = 0; i < _delayLoadingConstraints.Length; i++) { if (_delayLoadingConstraints[i] is UniqueConstraint) { if (_fLoadForeignKeyConstraintsOnly) { continue; } UniqueConstraint constr = (UniqueConstraint)_delayLoadingConstraints[i]; if (constr._columnNames == null) { Add(constr); continue; } colCount = constr._columnNames.Length; parents = new DataColumn[colCount]; for (int j = 0; j < colCount; j++) { parents[j] = _table.Columns[constr._columnNames[j]]; } if (constr._bPrimaryKey) { if (_table._primaryKey != null) { throw ExceptionBuilder.AddPrimaryKeyConstraint(); } else { Add(constr.ConstraintName, parents, true); } continue; } UniqueConstraint newConstraint = new UniqueConstraint(constr._constraintName, parents); if (FindConstraint(newConstraint) == null) { Add(newConstraint); } } else { ForeignKeyConstraint constr = (ForeignKeyConstraint)_delayLoadingConstraints[i]; if (constr._parentColumnNames == null || constr._childColumnNames == null) { Add(constr); continue; } if (_table.DataSet == null) { _fLoadForeignKeyConstraintsOnly = true; continue; } colCount = constr._parentColumnNames.Length; parents = new DataColumn[colCount]; childs = new DataColumn[colCount]; for (int j = 0; j < colCount; j++) { if (constr._parentTableNamespace == null) { parents[j] = _table.DataSet.Tables[constr._parentTableName].Columns[constr._parentColumnNames[j]]; } else { parents[j] = _table.DataSet.Tables[constr._parentTableName, constr._parentTableNamespace].Columns[constr._parentColumnNames[j]]; } childs[j] = _table.Columns[constr._childColumnNames[j]]; } ForeignKeyConstraint newConstraint = new ForeignKeyConstraint(constr._constraintName, parents, childs); newConstraint.AcceptRejectRule = constr._acceptRejectRule; newConstraint.DeleteRule = constr._deleteRule; newConstraint.UpdateRule = constr._updateRule; Add(newConstraint); } } if (!_fLoadForeignKeyConstraintsOnly) { _delayLoadingConstraints = null; } }
private void AddRowToTable(XmlNode tableNode, DataColumn relationColumn, bool inferSchema, bool fillRows) { Hashtable rowValue = new Hashtable(); DataTable table; // Check if the table exists in the DataSet. If not create one. if (DSet.Tables.Contains(tableNode.LocalName)) { table = DSet.Tables[tableNode.LocalName]; } else if (inferSchema) { table = new DataTable(tableNode.LocalName); DSet.Tables.Add(table); } else { return; } // For elements that are inferred as tables and that contain text // but have no child elements, a new column named "TableName_Text" // is created for the text of each of the elements. // If an element is inferred as a table and has text, but also has child elements, // the text is ignored. // Note : if an element is inferred as a table and has text // and has no child elements, // but the repeated ements of this table have child elements, // then the text is ignored. if (!HaveChildElements(tableNode) && HaveText(tableNode) && !IsRepeatedHaveChildNodes(tableNode)) { string columnName = tableNode.Name + "_Text"; if (!table.Columns.Contains(columnName)) { table.Columns.Add(columnName); } rowValue.Add(columnName, tableNode.InnerText); } // Get the child nodes of the table. Any child can be one of the following tow: // 1. DataTable - if there was a relation with another table.. // 2. DataColumn - column of the current table. XmlNodeList childList = tableNode.ChildNodes; for (int i = 0; i < childList.Count; i++) { XmlNode childNode = childList[i]; // we are looping through elements only // Note : if an element is inferred as a table and has text, but also has child elements, // the text is ignored. if (childNode.NodeType != XmlNodeType.Element) { continue; } // Elements that have attributes are inferred as tables. // Elements that have child elements are inferred as tables. // Elements that repeat are inferred as a single table. if (IsInferredAsTable(childNode)) { // child node inferred as table if (inferSchema) { // We need to create new column for the relation between the current // table and the new table we found (the child table). string newRelationColumnName = table.TableName + "_Id"; if (!table.Columns.Contains(newRelationColumnName)) { DataColumn newRelationColumn = new DataColumn(newRelationColumnName, typeof(int)); newRelationColumn.AllowDBNull = false; newRelationColumn.AutoIncrement = true; // we do not want to serialize this column so MappingType is Hidden. newRelationColumn.ColumnMapping = MappingType.Hidden; table.Columns.Add(newRelationColumn); } // Add a row to the new table we found. AddRowToTable(childNode, table.Columns[newRelationColumnName], inferSchema, fillRows); } else { AddRowToTable(childNode, null, inferSchema, fillRows); } } else { // Elements that have no attributes or child elements, and do not repeat, // are inferred as columns. object val = null; if (childNode.FirstChild != null) { val = childNode.FirstChild.Value; } else { val = ""; } if (table.Columns.Contains(childNode.LocalName)) { rowValue.Add(childNode.LocalName, val); } else if (inferSchema) { table.Columns.Add(childNode.LocalName); rowValue.Add(childNode.LocalName, val); } } } // Column can be attribute of the table element. XmlAttributeCollection aCollection = tableNode.Attributes; for (int i = 0; i < aCollection.Count; i++) { XmlAttribute attr = aCollection[i]; //the atrribute can be the namespace. if (attr.Prefix.Equals("xmlns")) { table.Namespace = attr.Value; } else // the attribute is a column. { if (!table.Columns.Contains(attr.LocalName)) { DataColumn col = table.Columns.Add(attr.LocalName); col.ColumnMapping = MappingType.Attribute; } table.Columns[attr.LocalName].Namespace = table.Namespace; rowValue.Add(attr.LocalName, attr.Value); } } // If the current table is a child table we need to add a new column for the relation // and add a new relation to the DataSet. if (relationColumn != null) { if (!table.Columns.Contains(relationColumn.ColumnName)) { DataColumn dc = new DataColumn(relationColumn.ColumnName, typeof(int)); // we do not want to serialize this column so MappingType is Hidden. dc.ColumnMapping = MappingType.Hidden; table.Columns.Add(dc); // Convention of relation name is: ParentTableName_ChildTableName DataRelation dr = new DataRelation(relationColumn.Table.TableName + "_" + dc.Table.TableName, relationColumn, dc); dr.Nested = true; DSet.Relations.Add(dr); UniqueConstraint.SetAsPrimaryKey(dr.ParentTable.Constraints, dr.ParentKeyConstraint); } rowValue.Add(relationColumn.ColumnName, relationColumn.GetAutoIncrementValue()); } // Create new row and add all values to the row. // then add it to the table. DataRow row = table.NewRow(); IDictionaryEnumerator enumerator = rowValue.GetEnumerator(); while (enumerator.MoveNext()) { row [enumerator.Key.ToString()] = StringToObject(table.Columns[enumerator.Key.ToString()].DataType, enumerator.Value.ToString()); } if (fillRows) { table.Rows.Add(row); } }
/// <summary> /// Get Extended Property from Object /// </summary> /// <param name="obj">Data Object</param> /// <param name="propName">Property Name</param> /// <returns>Property Value</returns> public static string GetExtendedProperty(object obj, string propName) { if (obj is System.Data.DataSet) { System.Data.DataSet dataSet = obj as System.Data.DataSet; if (dataSet.ExtendedProperties.Contains(propName)) { return((string)dataSet.ExtendedProperties[propName]); } return(null); } if (obj is System.Data.DataTable) { System.Data.DataTable dataTable = obj as System.Data.DataTable; if (dataTable.ExtendedProperties.Contains(propName)) { return((string)dataTable.ExtendedProperties[propName]); } return(null); } if (obj is System.Data.DataColumn) { System.Data.DataColumn dataColumn = obj as System.Data.DataColumn; if (dataColumn.ExtendedProperties.Contains(propName)) { return((string)dataColumn.ExtendedProperties[propName]); } return(null); } if (obj is System.Data.DataRelation) { System.Data.DataRelation dataRelation = obj as System.Data.DataRelation; if (dataRelation.ExtendedProperties.Contains(propName)) { return((string)dataRelation.ExtendedProperties[propName]); } return(null); } if (obj is System.Data.UniqueConstraint) { System.Data.UniqueConstraint uc = obj as System.Data.UniqueConstraint; if (uc.ExtendedProperties.Contains(propName)) { return((string)uc.ExtendedProperties[propName]); } return(null); } if (obj is System.Data.ForeignKeyConstraint) { System.Data.ForeignKeyConstraint fkc = obj as System.Data.ForeignKeyConstraint; if (fkc.ExtendedProperties.Contains(propName)) { return((string)fkc.ExtendedProperties[propName]); } return(null); } return(null); }
// To add foreign key constraint without adding any unique constraint for internal use. Main purpose : Binary Remoting internal void Add(Constraint constraint, bool addUniqueWhenAddingForeign) { if (constraint == null) { throw ExceptionBuilder.ArgumentNull(nameof(constraint)); } // It is an error if we find an equivalent constraint already in collection if (FindConstraint(constraint) != null) { throw ExceptionBuilder.DuplicateConstraint(FindConstraint(constraint).ConstraintName); } if (1 < _table.NestedParentRelations.Length) { if (!AutoGenerated(constraint)) { throw ExceptionBuilder.CantAddConstraintToMultipleNestedTable(_table.TableName); } } if (constraint is UniqueConstraint) { if (((UniqueConstraint)constraint)._bPrimaryKey) { if (Table._primaryKey != null) { throw ExceptionBuilder.AddPrimaryKeyConstraint(); } } AddUniqueConstraint((UniqueConstraint)constraint); } else if (constraint is ForeignKeyConstraint) { ForeignKeyConstraint fk = (ForeignKeyConstraint)constraint; if (addUniqueWhenAddingForeign) { UniqueConstraint key = fk.RelatedTable.Constraints.FindKeyConstraint(fk.RelatedColumnsReference); if (key == null) { if (constraint.ConstraintName.Length == 0) { constraint.ConstraintName = AssignName(); } else { RegisterName(constraint.ConstraintName); } key = new UniqueConstraint(fk.RelatedColumnsReference); fk.RelatedTable.Constraints.Add(key); } } AddForeignKeyConstraint((ForeignKeyConstraint)constraint); } BaseAdd(constraint); ArrayAdd(constraint); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, constraint)); if (constraint is UniqueConstraint) { if (((UniqueConstraint)constraint)._bPrimaryKey) { Table.PrimaryKey = ((UniqueConstraint)constraint).ColumnsReference; } } }
internal void SetParentKeyConstraint(UniqueConstraint uniqueConstraint) { parentKeyConstraint = uniqueConstraint; }
public static Exception NeededForForeignKeyConstraint(UniqueConstraint key, ForeignKeyConstraint fk) => _Argument(SR.Format(SR.DataConstraint_NeededForForeignKeyConstraint, key.ConstraintName, fk.ConstraintName));
internal void SetParentKeyConstraint(UniqueConstraint value) { Debug.Assert(_parentKeyConstraint == null || value == null, "ParentKeyConstraint should not have been set already."); _parentKeyConstraint = value; }
protected override void AddCore(DataRelation relation) { base.AddCore(relation); if ((relation.ChildTable.DataSet != this.dataSet) || (relation.ParentTable.DataSet != this.dataSet)) { throw ExceptionBuilder.ForeignRelation(); } relation.CheckState(); if (relation.Nested) { relation.CheckNestedRelations(); } if (relation.relationName.Length == 0) { relation.relationName = base.AssignName(); } else { base.RegisterName(relation.relationName); } DataKey childKey = relation.ChildKey; for (int i = 0; i < this.relations.Count; i++) { if (childKey.ColumnsEqual(((DataRelation)this.relations[i]).ChildKey) && relation.ParentKey.ColumnsEqual(((DataRelation)this.relations[i]).ParentKey)) { throw ExceptionBuilder.RelationAlreadyExists(); } } this.relations.Add(relation); ((DataRelationCollection.DataTableRelationCollection)relation.ParentTable.ChildRelations).Add(relation); ((DataRelationCollection.DataTableRelationCollection)relation.ChildTable.ParentRelations).Add(relation); relation.SetDataSet(this.dataSet); relation.ChildKey.GetSortIndex().AddRef(); if (relation.Nested) { relation.ChildTable.CacheNestedParent(); } ForeignKeyConstraint constraint = relation.ChildTable.Constraints.FindForeignKeyConstraint(relation.ParentColumnsReference, relation.ChildColumnsReference); if (relation.createConstraints && (constraint == null)) { relation.ChildTable.Constraints.Add(constraint = new ForeignKeyConstraint(relation.ParentColumnsReference, relation.ChildColumnsReference)); try { constraint.ConstraintName = relation.RelationName; } catch (Exception exception) { if (!ADP.IsCatchableExceptionType(exception)) { throw; } ExceptionBuilder.TraceExceptionWithoutRethrow(exception); } } UniqueConstraint constraint2 = relation.ParentTable.Constraints.FindKeyConstraint(relation.ParentColumnsReference); relation.SetParentKeyConstraint(constraint2); relation.SetChildKeyConstraint(constraint); }
protected override void AddCore(DataRelation relation) { base.AddCore(relation); if (relation.ChildTable.DataSet != _dataSet || relation.ParentTable.DataSet != _dataSet) { throw ExceptionBuilder.ForeignRelation(); } relation.CheckState(); if (relation.Nested) { relation.CheckNestedRelations(); } if (relation._relationName.Length == 0) { relation._relationName = AssignName(); } else { RegisterName(relation._relationName); } DataKey childKey = relation.ChildKey; for (int i = 0; i < _relations.Count; i++) { if (childKey.ColumnsEqual(((DataRelation)_relations[i]).ChildKey)) { if (relation.ParentKey.ColumnsEqual(((DataRelation)_relations[i]).ParentKey)) { throw ExceptionBuilder.RelationAlreadyExists(); } } } _relations.Add(relation); ((DataTableRelationCollection)(relation.ParentTable.ChildRelations)).Add(relation); // Caching in ParentTable -> ChildRelations ((DataTableRelationCollection)(relation.ChildTable.ParentRelations)).Add(relation); // Caching in ChildTable -> ParentRelations relation.SetDataSet(_dataSet); relation.ChildKey.GetSortIndex().AddRef(); if (relation.Nested) { relation.ChildTable.CacheNestedParent(); } ForeignKeyConstraint foreignKey = relation.ChildTable.Constraints.FindForeignKeyConstraint(relation.ParentColumnsReference, relation.ChildColumnsReference); if (relation._createConstraints) { if (foreignKey == null) { relation.ChildTable.Constraints.Add(foreignKey = new ForeignKeyConstraint(relation.ParentColumnsReference, relation.ChildColumnsReference)); // try to name the fk constraint the same as the parent relation: try { foreignKey.ConstraintName = relation.RelationName; } catch (Exception e) when(Common.ADP.IsCatchableExceptionType(e)) { ExceptionBuilder.TraceExceptionWithoutRethrow(e); } } } UniqueConstraint key = relation.ParentTable.Constraints.FindKeyConstraint(relation.ParentColumnsReference); relation.SetParentKeyConstraint(key); relation.SetChildKeyConstraint(foreignKey); }
// Add unique constaraints to the schema. // return hashtable with the names of all XmlSchemaUnique elements we created. private void AddUniqueConstraints(UniqueConstraint uniq, ArrayList names) { // if column of the constraint is hidden do not write the constraint. foreach (DataColumn column in uniq.Columns) { if (column.ColumnMapping == MappingType.Hidden) { return; // do nothing } } w.WriteStartElement("xs", "unique", xmlnsxs); // if constaraint name do not exist in the hashtable we can use it. string name; if (!names.Contains(uniq.ConstraintName)) { name = XmlHelper.Encode(uniq.ConstraintName); w.WriteAttributeString("name", name); } // otherwise generate new constraint name for the // XmlSchemaUnique element. else { name = XmlHelper.Encode(uniq.Table.TableName) + "_" + XmlHelper.Encode(uniq.ConstraintName); w.WriteAttributeString("name", name); w.WriteAttributeString( XmlConstants.MsdataPrefix, XmlConstants.ConstraintName, XmlConstants.MsdataNamespace, XmlHelper.Encode(uniq.ConstraintName)); } names.Add(name); if (uniq.IsPrimaryKey) { w.WriteAttributeString( XmlConstants.MsdataPrefix, XmlConstants.PrimaryKey, XmlConstants.MsdataNamespace, "true"); } AddExtendedPropertyAttributes(uniq.ExtendedProperties); w.WriteStartElement("xs", "selector", xmlnsxs); w.WriteAttributeString("xpath", ".//" + ConstraintPrefix + XmlHelper.Encode(uniq.Table.TableName)); w.WriteEndElement(); // selector foreach (DataColumn c in uniq.Columns) { w.WriteStartElement("xs", "field", xmlnsxs); w.WriteStartAttribute("xpath", String.Empty); if (c.ColumnMapping == MappingType.Attribute) { w.WriteString("@"); } w.WriteString(ConstraintPrefix); w.WriteString(XmlHelper.Encode(c.ColumnName)); w.WriteEndAttribute(); // xpath w.WriteEndElement(); // field } w.WriteEndElement(); // unique }
void CreateData() { try { connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Projects\\Firma.mdb;Persist Security Info=True"; OleDbConnection cn = new OleDbConnection(connectionString); dsUntyped = new DataSet("DataSetUntyped"); //dsUntyped.EnforceConstraints = false; // dodavanje tablica, punjenje tablica, mapiranje oleDbDataAdapterDokument = new OleDbDataAdapter( "SELECT IdOsobe AS IdPartnera, PrezimeOsobe+ImeOsobe AS Naziv, JMBG AS Broj FROM Osoba" + " UNION " + "SELECT IdTvrtke AS IdPartnera, NazivTvrtke AS Naziv, MatBrTvrtke AS Broj FROM Tvrtka", cn); oleDbDataAdapterDokument.TableMappings.Add("Table", "Partner"); oleDbDataAdapterDokument.Fill(dsUntyped); #region DinamickiNapravljenaTablica oleDbDataAdapterStavka = new OleDbDataAdapter("SELECT * FROM Dokument", cn); DataTable dt = new DataTable("Dokument"); dt.Columns.Add("IdDokumenta", typeof(int)); dt.Columns.Add("VrDokumenta", typeof(string)); dt.Columns.Add("BrDokumenta", typeof(int)); dt.Columns.Add("DatDokumenta", typeof(System.DateTime)); dt.Columns.Add("IdPartnera", typeof(int)); //dt.Columns.Add("IznosDokumenta", typeof(decimal)); dsUntyped.Tables.Add(dt); // ukoliko se ne navede, adapter generira shemu, unatoè mapping oleDbDataAdapterStavka.MissingSchemaAction = MissingSchemaAction.Ignore; //oleDbDataAdapterStavka.TableMappings.Add("Table", "Dokument"); //oleDbDataAdapterStavka.TableMappings[0].ColumnMappings.Add("IdDokumenta","IdDokumenta"); //oleDbDataAdapterStavka.TableMappings[0].ColumnMappings.Add("VrDokumenta","VrDokumenta"); //oleDbDataAdapterStavka.TableMappings[0].ColumnMappings.Add("BrDokumenta","BrDokumenta"); //oleDbDataAdapterStavka.TableMappings[0].ColumnMappings.Add("DatDokumenta","DatDokumenta"); //oleDbDataAdapterStavka.TableMappings[0].ColumnMappings.Add("IdPartnera","IdPartnera"); oleDbDataAdapterStavka.Fill(dsUntyped, "Dokument"); // dinamicko kreiranje stranog kljuca //ForeignKeyConstraint fk; //fk = new System.Data.ForeignKeyConstraint("FK_Partner_Dokument", //dsUntyped.Tables["Partner"].Columns["IdPartnera"], //dsUntyped.Tables["Dokument"].Columns["Idpartnera"]); //dsUntyped.Tables["Dokument"].Constraints.Add(fk); // dinamicko kreiranje ogranicenja na jedinstvene vrijednosti UniqueConstraint uc; uc = new System.Data.UniqueConstraint("NewUnique", new DataColumn[] { dt.Columns["VrDokumenta"], dt.Columns["BrDokumenta"] } , false); // dt.Columns["IdDokumenta"]); // bez new dt.Constraints.Add(uc); #endregion // dodavanje veze FK_Dokument_Stavka DataRelation relOrdDet; DataColumn colMaster; DataColumn colDetail; colMaster = dsUntyped.Tables["Partner"].Columns["IdPartnera"]; colDetail = dsUntyped.Tables["Dokument"].Columns["IdPartnera"]; relOrdDet = new DataRelation("FK_Partner_Dokument", colMaster, colDetail); dsUntyped.Relations.Add(relOrdDet); //expression dsUntyped.Tables["Partner"].Columns.Add( new DataColumn( "BrojDokumenata", typeof(float), "Count(Child(FK_Partner_Dokument).IdDokumenta)") ); // alternativa za tipove: Type.GetType("System.Float") //, ("System.Int32"), ("System.String") } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private static bool AdjustSchemaRelations(DataSet targetSet, DataSet sourceSet, MissingSchemaAction missingSchemaAction) { if (missingSchemaAction == MissingSchemaAction.Ignore) { return(true); } foreach (DataTable sourceTable in sourceSet.Tables) { DataTable targetTable = targetSet.Tables[sourceTable.TableName]; if (targetTable == null) { continue; } foreach (Constraint constraint in sourceTable.Constraints) { Constraint targetConstraint = null; string constraintName = constraint.ConstraintName; if (targetTable.Constraints.Contains(constraintName)) { constraintName = ""; } UniqueConstraint uc = constraint as UniqueConstraint; // PrimaryKey is already taken care of while merging the table // ForeignKey constraint takes care of Parent Unique Constraints if (uc != null) { if (uc.IsPrimaryKey || uc.ChildConstraint != null) { continue; } DataColumn[] columns = ResolveColumns(targetTable, uc.Columns); targetConstraint = new UniqueConstraint(constraintName, columns, false); } ForeignKeyConstraint fc = constraint as ForeignKeyConstraint; if (fc != null) { DataColumn[] columns = ResolveColumns(targetTable, fc.Columns); DataColumn[] relatedColumns = ResolveColumns(targetSet.Tables [fc.RelatedTable.TableName], fc.RelatedColumns); targetConstraint = new ForeignKeyConstraint(constraintName, relatedColumns, columns); } bool dupConstraintFound = false; foreach (Constraint cons in targetTable.Constraints) { if (!targetConstraint.Equals(cons)) { continue; } dupConstraintFound = true; break; } // If equivalent-constraint already exists, then just do nothing if (dupConstraintFound) { continue; } if (missingSchemaAction == MissingSchemaAction.Error) { throw new DataException("Target DataSet missing " + targetConstraint.GetType() + targetConstraint.ConstraintName); } else { targetTable.Constraints.Add(targetConstraint); } } } foreach (DataRelation relation in sourceSet.Relations) { DataRelation targetRelation = targetSet.Relations [relation.RelationName]; if (targetRelation == null) { if (missingSchemaAction == MissingSchemaAction.Error) { throw new ArgumentException("Target DataSet mising definition for " + relation.RelationName); } DataColumn[] parentColumns = ResolveColumns(targetSet.Tables [relation.ParentTable.TableName], relation.ParentColumns); DataColumn[] childColumns = ResolveColumns(targetSet.Tables [relation.ChildTable.TableName], relation.ChildColumns); targetRelation = targetSet.Relations.Add(relation.RelationName, parentColumns, childColumns, relation.createConstraints); targetRelation.Nested = relation.Nested; } else if (!CompareColumnArrays(relation.ParentColumns, targetRelation.ParentColumns) || !CompareColumnArrays(relation.ChildColumns, targetRelation.ChildColumns)) { RaiseMergeFailedEvent(null, "Relation " + relation.RelationName + " cannot be merged, because keys have mismatch columns."); } } return(true); }
internal void SetParentKeyConstraint(UniqueConstraint value) { this.parentKeyConstraint = value; }