//private void SetDrivedEntites(int defaultEntityID)
        //{



        //}

        private void cmbDrivedEntities_SelectionChangeCommitted(object sender, EventArgs e)
        {
            txtName.Text     = "";
            txtCriteria.Text = "";
            dtgRelationshipsDrived.DataSource = new ObservableCollection <RelationshipDTO>();
            dtgColumnsDrived.DataSource       = new ObservableCollection <ColumnDTO>();

            var id           = (cmbDrivedEntities.SelectedValue == null ? 0 : (int)cmbDrivedEntities.SelectedValue);
            var drivedEntity = DrivedEntities.FirstOrDefault(x => x.ID == id);

            if (drivedEntity != null)
            {
                txtName.Text     = drivedEntity.Name;
                txtCriteria.Text = drivedEntity.Criteria;
                using (var projectContext = new DataAccess.MyProjectEntities())
                {
                    var dbDrivedEntity = projectContext.TableDrivedEntity.First(x => x.ID == drivedEntity.ID);



                    ObservableCollection <RelationshipDTO> drivedRelationships = new ObservableCollection <RelationshipDTO>();
                    foreach (var dbRelationship in dbDrivedEntity.Relationship.Where(
                                 x => !(x.TableDrivedEntity.TableID == x.TableDrivedEntity1.TableID && (x.RelationshipType.SuperToSubRelationshipType != null || x.RelationshipType.SubToSuperRelationshipType != null))
                                 ))
                    {
                        drivedRelationships.Add(GeneralHelper.ToRelationshipDTO(dbRelationship));
                    }
                    dtgRelationshipsDrived.DataSource = drivedRelationships;

                    ObservableCollection <ColumnDTO> drivedColumns = new ObservableCollection <ColumnDTO>();
                    foreach (var dbColumn in dbDrivedEntity.Column)
                    {
                        drivedColumns.Add(GeneralHelper.ToColumnDTO(dbColumn));
                    }
                    dtgColumnsDrived.DataSource = drivedColumns;
                }
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            //ستونهای رابطه برای مشتقها از موجودیت پایه حذف شوند
            //کد نوشته شود
            if (txtName.Text == "")
            {
                MessageBox.Show("نام موجودیت مشخص نشده است", "نام موجودیت");
                return;
            }
            if ((cmbDrivedEntities.SelectedValue == null ? 0 : (int)cmbDrivedEntities.SelectedValue) == BaseEntity.ID)
            {
                if (txtCriteria.Text != "")
                {
                    MessageBox.Show("برای موجودیت پایه شرط نمیتوان تعریف نمود", "شرط موجودیت");
                    return;
                }
            }
            else
            {
                if (txtCriteria.Text == "")
                {
                    MessageBox.Show("شرط موجودیت مشخص نشده است", "شرط موجودیت");
                    return;
                }
            }
            if (Inheritance)
            {
                if (!optIsDisjoint.Checked && !optIsOverlap.Checked)
                {
                    MessageBox.Show("نوع رابطه ارث بری مشخص نشده است", "Disjoint or Overlap");
                    return;
                }
                if (!optIsTolatParticipation.Checked && !optIsPartialParticipation.Checked)
                {
                    MessageBox.Show("نوع رابطه ارث بری مشخص نشده است", "TolatParticipation or PartialParticipatio");
                    return;
                }
            }
            using (var projectContext = new DataAccess.MyProjectEntities())
            {
                if (!Inheritance || (cmbDrivedEntities.SelectedValue == null ? 0 : (int)cmbDrivedEntities.SelectedValue) == BaseEntity.ID)
                {
                    var columnMessage  = "";
                    var baseColumns    = dtgColumns.DataSource as ObservableCollection <ColumnDTO>;
                    var derivedColumns = dtgColumnsDrived.DataSource as ObservableCollection <ColumnDTO>;
                    List <ColumnDTO> unSelectedAndNotNullable = new List <ColumnDTO>();
                    foreach (var column in baseColumns)
                    {
                        var dbColumn = projectContext.Column.First(x => x.ID == column.ID);
                        if (dbColumn.IsNull == false)
                        {
                            if (!derivedColumns.Any(x => x.ID == column.ID))
                            {
                                unSelectedAndNotNullable.Add(column);
                                columnMessage += (columnMessage == "" ? "" : Environment.NewLine) + "ستون " + column.Name;
                            }
                        }
                    }
                    if (columnMessage != "")
                    {
                        var message = " ستونهای زیر مقادیر اجباری میگیرند و انتخاب آنها اجباری میباشد" + Environment.NewLine + columnMessage;
                        MessageBox.Show(message, "ستونهای اجباری");
                        return;
                    }
                }



                //انتخاب ستونهای روابط

                //if (Duplicate)
                //{
                //var baseEntity = projectContext.TableDrivedEntity.First(x => x.ID == BaseEntity.ID);
                //baseEntity.Column.Clear();
                //foreach (var item in dtgColumns.DataSource as ObservableCollection<ColumnDTO>)
                //{
                //    baseEntity.Column.Add(projectContext.Column.First(x => x.ID == item.ID));
                //}



                var id           = (cmbDrivedEntities.SelectedValue == null ? 0 : (int)cmbDrivedEntities.SelectedValue);
                var drivedEntity = projectContext.TableDrivedEntity.FirstOrDefault(x => x.ID == id);
                if (drivedEntity == null)
                {
                    drivedEntity = new TableDrivedEntity();

                    drivedEntity.IndependentDataEntry = BaseEntity.IndependentDataEntry;
                    drivedEntity.TableID = BaseEntity.TableID;
                }
                drivedEntity.Name     = txtName.Text;
                drivedEntity.Criteria = txtCriteria.Text;
                drivedEntity.Column.Clear();
                foreach (var item in dtgColumnsDrived.DataSource as ObservableCollection <ColumnDTO> )
                {
                    drivedEntity.Column.Add(projectContext.Column.First(x => x.ID == item.ID));
                }
                foreach (var item in dtgRelationshipsDrived.DataSource as ObservableCollection <RelationshipDTO> )
                {
                    Relationship dbReverseRelationship = null;
                    var          dbRelationship        = projectContext.Relationship.First(x => x.ID == item.ID);
                    if (dbRelationship.Relationship2 != null)
                    {
                        dbReverseRelationship = dbRelationship.Relationship2;
                    }
                    else
                    {
                        dbReverseRelationship = projectContext.Relationship.First(x => x.RelationshipID == item.ID);
                    }

                    if (dbRelationship.TableDrivedEntity.TableID == BaseEntity.TableID)
                    {
                        if (dbRelationship.Relationship2 == null)
                        {
                            dbRelationship.Name = dbRelationship.Name.Replace("(PK)" + dbRelationship.TableDrivedEntity.Name + ".", "(PK)" + drivedEntity.Name + ".");
                        }
                        else
                        {
                            dbRelationship.Name = dbRelationship.Name.Replace("(FK)" + dbRelationship.TableDrivedEntity.Name + ".", "(FK)" + drivedEntity.Name + ".");
                        }

                        dbRelationship.TableDrivedEntity = drivedEntity;
                    }
                    if (dbRelationship.TableDrivedEntity1.TableID == BaseEntity.TableID)
                    {
                        if (dbRelationship.Relationship2 == null)
                        {
                            dbRelationship.Name = dbRelationship.Name.Replace("(FK)" + dbRelationship.TableDrivedEntity.Name + ".", "(FK)" + drivedEntity.Name + ".");
                        }
                        else
                        {
                            dbRelationship.Name = dbRelationship.Name.Replace("(PK)" + dbRelationship.TableDrivedEntity.Name + ".", "(PK)" + drivedEntity.Name + ".");
                        }
                        dbRelationship.TableDrivedEntity1 = drivedEntity;
                    }

                    if (dbReverseRelationship.TableDrivedEntity.TableID == BaseEntity.TableID)
                    {
                        if (dbReverseRelationship.Relationship2 == null)
                        {
                            dbReverseRelationship.Name = dbReverseRelationship.Name.Replace("(PK)" + dbRelationship.TableDrivedEntity.Name + ".", "(PK)" + drivedEntity.Name + ".");
                        }
                        else
                        {
                            dbReverseRelationship.Name = dbReverseRelationship.Name.Replace("(FK)" + dbRelationship.TableDrivedEntity.Name + ".", "(FK)" + drivedEntity.Name + ".");
                        }
                        dbReverseRelationship.TableDrivedEntity = drivedEntity;
                    }
                    if (dbReverseRelationship.TableDrivedEntity1.TableID == BaseEntity.TableID)
                    {
                        if (dbReverseRelationship.Relationship2 == null)
                        {
                            dbReverseRelationship.Name = dbReverseRelationship.Name.Replace("(FK)" + dbRelationship.TableDrivedEntity.Name + ".", "(FK)" + drivedEntity.Name + ".");
                        }
                        else
                        {
                            dbReverseRelationship.Name = dbReverseRelationship.Name.Replace("(PK)" + dbRelationship.TableDrivedEntity.Name + ".", "(PK)" + drivedEntity.Name + ".");
                        }
                        dbReverseRelationship.TableDrivedEntity1 = drivedEntity;
                    }
                }
                if (Inheritance && !((cmbDrivedEntities.SelectedValue == null ? 0 : (int)cmbDrivedEntities.SelectedValue) == BaseEntity.ID))
                {
                    DataAccess.ISARelationship isaRelationship = null;
                    var existingEntity = DrivedEntities.FirstOrDefault(x => x.ID != BaseEntity.ID && x.ID != 0);
                    if (existingEntity != null)
                    {
                        var sampleSuperToSub = projectContext.Relationship.FirstOrDefault(x => x.TableDrivedEntityID1 == BaseEntity.ID && x.TableDrivedEntityID2 == existingEntity.ID && x.RelationshipType != null &&
                                                                                          x.RelationshipType.SuperToSubRelationshipType != null);
                        if (sampleSuperToSub != null)
                        {
                            isaRelationship = sampleSuperToSub.RelationshipType.SuperToSubRelationshipType.ISARelationship;
                        }
                        else
                        {
                            throw (new Exception("ISARelationship cound not be found!"));
                        }
                    }

                    if (isaRelationship == null)
                    {
                        isaRelationship = new ISARelationship();
                    }
                    isaRelationship.IsTolatParticipation = optIsTolatParticipation.Checked == true;
                    isaRelationship.IsDisjoint           = optIsDisjoint.Checked == true;

                    string subTypesStr = "";
                    foreach (var drivedentity in DrivedEntities)
                    {
                        if (drivedentity.ID != BaseEntity.ID)
                        {
                            subTypesStr += (subTypesStr == "" ? "" : ",") + drivedentity.Name;
                        }
                    }
                    if (drivedEntity.ID == 0)
                    {
                        subTypesStr += (subTypesStr == "" ? "" : ",") + drivedEntity.Name;
                    }
                    isaRelationship.Name = BaseEntity.Name + ">" + subTypesStr;
                    if (drivedEntity.ID == 0)
                    {
                        var relationship = new Relationship();
                        relationship.RelationshipType = new RelationshipType();
                        relationship.RelationshipType.SuperToSubRelationshipType = new SuperToSubRelationshipType();
                        relationship.RelationshipType.IsOtherSideCreatable       = true;
                        relationship.TableDrivedEntityID1 = BaseEntity.ID;
                        relationship.RelationshipType.SuperToSubRelationshipType.ISARelationship = isaRelationship;
                        drivedEntity.Relationship1.Add(relationship);



                        var relationshipReverse = new Relationship();
                        relationshipReverse.RelationshipType = new RelationshipType();
                        relationshipReverse.RelationshipType.SubToSuperRelationshipType = new SubToSuperRelationshipType();
                        relationshipReverse.RelationshipType.IsOtherSideCreatable       = true;
                        relationshipReverse.TableDrivedEntityID2 = BaseEntity.ID;
                        relationshipReverse.RelationshipType.SubToSuperRelationshipType.ISARelationship = isaRelationship;
                        relationshipReverse.Relationship2 = relationship;
                        drivedEntity.Relationship.Add(relationshipReverse);

                        var    dbBaseEntity = projectContext.TableDrivedEntity.First(x => x.ID == BaseEntity.ID);
                        string PKColumns    = "";
                        string FKColumns    = "";
                        foreach (var primaryCol in dbBaseEntity.Table.Column.Where(x => x.PrimaryKey == true))
                        {
                            PKColumns += (PKColumns == "" ? "" : ",") + primaryCol.Name;
                            FKColumns += (FKColumns == "" ? "" : ",") + primaryCol.Name;
                            relationship.RelationshipColumns.Add(new RelationshipColumns()
                            {
                                Column = primaryCol, Column1 = primaryCol
                            });
                            relationshipReverse.RelationshipColumns.Add(new RelationshipColumns()
                            {
                                Column = primaryCol, Column1 = primaryCol
                            });
                        }
                        relationship.Name        = "(PK)" + BaseEntity.Name + "." + PKColumns + ">(FK)" + drivedEntity.Name + "." + FKColumns;
                        relationshipReverse.Name = "(FK)" + drivedEntity.Name + "." + FKColumns + ">(PK)" + BaseEntity.Name + "." + PKColumns;
                    }
                }
                if (drivedEntity.ID == 0)
                {
                    projectContext.TableDrivedEntity.Add(drivedEntity);
                }
                projectContext.SaveChanges();
                SetEntities(drivedEntity.ID);
            }


            //this.Close();
            //}
            //else
            //{
            //    var editEntity = projectContext.TableDrivedEntity.First(x => x.ID == MainEntity.ID);
            //    editEntity.Column.Clear();
            //    foreach (var item in dtgColumns.DataSource as List<ColumnDTO>)
            //    {
            //        if (item.Select)
            //            editEntity.Column.Add(projectContext.Column.First(x => x.ID == item.ID));
            //    }
            //    if (tabControl1.TabPages.Contains(tabRelationship))
            //    {
            //        foreach (var item in dtgRelationships.DataSource as List<RelationshipDTO>)
            //        {
            //            if (item.Select)
            //            {
            //                Relationship dbReverseRelationship = null;
            //                var dbRelationship = projectContext.Relationship.First(x => x.ID == item.ID);
            //                if (dbRelationship.Relationship2 != null)
            //                    dbReverseRelationship = dbRelationship.Relationship2;
            //                else
            //                    dbReverseRelationship = projectContext.Relationship.First(x => x.RelationshipID == item.ID);

            //                if (dbRelationship.TableDrivedEntity.TableDrivedEntity.TableID == MainEntity.TableID)
            //                {
            //                    if (dbRelationship.Relationship2 == null)
            //                        dbRelationship.Name = dbRelationship.Name.Replace("(PK)" + dbRelationship.TableDrivedEntity.Name + ".", "(PK)" + MainEntity.Name + ".");
            //                    else
            //                        dbRelationship.Name = dbRelationship.Name.Replace("(FK)" + dbRelationship.TableDrivedEntity.Name + ".", "(FK)" + MainEntity.Name + ".");
            //                    dbRelationship.TableDrivedEntity = editEntity;
            //                }
            //                if (dbRelationship.Entity1.TableDrivedEntity.TableID == MainEntity.TableID)
            //                {
            //                    if (dbRelationship.Relationship2 == null)
            //                        dbRelationship.Name = dbRelationship.Name.Replace("(FK)" + dbRelationship.TableDrivedEntity.Name + ".", "(FK)" + MainEntity.Name + ".");
            //                    else
            //                        dbRelationship.Name = dbRelationship.Name.Replace("(PK)" + dbRelationship.TableDrivedEntity.Name + ".", "(PK)" + MainEntity.Name + ".");
            //                    dbRelationship.Entity1 = editEntity;
            //                }
            //                if (dbReverseRelationship.TableDrivedEntity.TableDrivedEntity.TableID == MainEntity.TableID)
            //                {
            //                    if (dbReverseRelationship.Relationship2 == null)
            //                        dbReverseRelationship.Name = dbReverseRelationship.Name.Replace("(PK)" + dbRelationship.TableDrivedEntity.Name + ".", "(PK)" + MainEntity.Name + ".");
            //                    else
            //                        dbReverseRelationship.Name = dbReverseRelationship.Name.Replace("(FK)" + dbRelationship.TableDrivedEntity.Name + ".", "(FK)" + MainEntity.Name + ".");
            //                    dbReverseRelationship.TableDrivedEntity = editEntity;
            //                }
            //                if (dbReverseRelationship.Entity1.TableDrivedEntity.TableID == MainEntity.TableID)
            //                {
            //                    if (dbReverseRelationship.Relationship2 == null)
            //                        dbReverseRelationship.Name = dbReverseRelationship.Name.Replace("(FK)" + dbRelationship.TableDrivedEntity.Name + ".", "(FK)" + MainEntity.Name + ".");
            //                    else
            //                        dbReverseRelationship.Name = dbReverseRelationship.Name.Replace("(PK)" + dbRelationship.TableDrivedEntity.Name + ".", "(PK)" + MainEntity.Name + ".");
            //                    dbReverseRelationship.Entity1 = editEntity;
            //                }

            //            }
            //        }
            //    }


            //    //try
            //    //{
            //    //projectContext.SaveChanges();
            //    //}
            //    //catch (System.Data.TableDrivedEntity.Validation.DbEntityValidationException ed)
            //    //{
            //    //    foreach (var eve in ed.EntityValidationErrors)
            //    //    {
            //    //        Console.WriteLine("TableDrivedEntity of type \"{0}\" in state \"{1}\" has the following validation errors:",
            //    //            eve.Entry.TableDrivedEntity.GetType().Name, eve.Entry.State);
            //    //        foreach (var ve in eve.ValidationErrors)
            //    //        {
            //    //            Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
            //    //                ve.PropertyName, ve.ErrorMessage);
            //    //        }
            //    //    }
            //    //    throw;
            //    //}
            //    // this.Close();
            //}
        }