karthik keyan

karthik keyan

  • NA
  • 1
  • 1.2k

ForeignKeyConstrain Not Working

Aug 24 2012 3:25 AM

hi i tried foreign key constraint in the following code,but not working (i.e not throws error when i tried to delete a row which is used by some other table),pls tell me know what is the issue on the following code

  try
            {
                int salesid = 2;


                DataSet ds1 = new DataSet();

                DataSet fakeDS = new DataSet();
                DataTable dt = null;
                fakeDS.ReadXml(@"product.xml");

                dt = fakeDS.Tables[0].Copy();
                dt.TableName = "product";
                ds1.Tables.Add(dt);

                DataSet fakeDS2 = new DataSet();
                DataTable dt2 = null;

                fakeDS2.ReadXml(@"sales.xml");

                dt2 = fakeDS2.Tables[0].Copy();
                dt2.TableName = "sales";
                ds1.Tables.Add(dt2);

                DataColumn dcParent, dcChild;

                dcChild = ds1.Tables["sales"].Columns["productid"];
                dcParent = ds1.Tables["product"].Columns["id"];
                
                ForeignKeyConstraint FKC = new ForeignKeyConstraint("foreignkeys", ds1.Tables["product"].Columns["id"], ds1.Tables["sales"].Columns["productid"]);
                FKC.DeleteRule = Rule.None;
                ds1.Tables[1].Constraints.Add(FKC);
                ds1.Tables[1].AcceptChanges();
                ds1.AcceptChanges();


                for (int i = 0; i < ds1.Tables[1].Rows.Count; i++)
                {
                    if (ds1.Tables[1].Rows[i]["salesid"].Equals(salesid.ToString()))
                    //if (ds1.Rows[i]["productid"].Equals(salesid.ToString()))
                    {
                        //dt2.Rows[i].Delete();
                        
                        ds1.Tables[1].Rows[i].Delete();
                    }
                }
            }
            catch (Exception ex1)
            {
                MessageBox.Show(ex1.Message.ToString());
            }