Example #1
0
            protected override void OnValueChanged(FieldBase element, bool oldValue, bool newValue)
            {
                base.OnValueChanged(element, oldValue, newValue);

                try
                {
                    if (element.Entity != null && element.Entity.nHydrateModel != null && !element.Entity.nHydrateModel.IsLoading)
                    {
                        //Processes Index list
                        if (newValue) //element.IsIndexed //Must use real property since there is logic there
                        {
                            //Add an Asc single field index
                            var existing = element.Entity.Indexes.FirstOrDefault(x => x.IndexColumns.Count == 1 && x.IndexColumns.First().FieldID == element.Id && x.IndexColumns.First().Ascending&& x.IndexType == IndexTypeConstants.IsIndexed);
                            if (existing == null)
                            {
                                using (var transaction = element.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
                                {
                                    var newIndex = new Index(element.Partition);
                                    newIndex.ParentEntityID = element.Entity.Id;
                                    newIndex.IndexType      = IndexTypeConstants.IsIndexed;
                                    newIndex.Clustered      = false;
                                    element.Entity.Indexes.Add(newIndex);

                                    var newColumn = new IndexColumn(element.Partition);
                                    newColumn.FieldID    = element.Id;
                                    newColumn.IsInternal = true;
                                    newIndex.IndexColumns.Add(newColumn);

                                    transaction.Commit();
                                }
                            }
                        }
                        else //Remove Index
                        {
                            var existingList = element.Entity.Indexes
                                               .Where(x => x.IndexType == IndexTypeConstants.IsIndexed && x.IndexColumns.Count == 1 && x.IndexColumns.First().FieldID == element.Id && x.IndexType == IndexTypeConstants.IsIndexed)
                                               .ToList();

                            using (var transaction = element.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
                            {
                                while (existingList.Count > 0)
                                {
                                    var item = existingList.First();
                                    item.IndexType = IndexTypeConstants.User;
                                    element.Entity.Indexes.Remove(item);
                                    existingList.Remove(item);
                                }
                                transaction.Commit();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
Example #2
0
        public static void LoadInitialIndexes(nHydrateModel modelRoot)
        {
            //Setup primary keys
            foreach (var entity in modelRoot.Entities)
            {
                if (entity.Indexes.Count(x => x.IndexType == IndexTypeConstants.PrimaryKey) == 0 && entity.PrimaryKeyFields.Count > 0)
                {
                    var newIndex = new Index(entity.Partition);
                    newIndex.ParentEntityID = entity.Id;
                    newIndex.IndexType      = IndexTypeConstants.PrimaryKey;
                    newIndex.Clustered      = true;
                    entity.Indexes.Add(newIndex);

                    foreach (var field in entity.PrimaryKeyFields)
                    {
                        var newColumn = new IndexColumn(field.Partition);
                        newColumn.FieldID    = field.Id;
                        newColumn.IsInternal = true;
                        newIndex.IndexColumns.Add(newColumn);
                    }
                }
            }

            var allIndexedField = modelRoot.Entities.SelectMany(x => x.Fields).Where(x => x.IsIndexed && !x.IsPrimaryKey);
            var allIndexes      = modelRoot.Entities.SelectMany(x => x.Indexes);

            foreach (var field in allIndexedField)
            {
                var index = allIndexes.FirstOrDefault(x =>
                                                      x.IndexColumns.Count == 1 &&
                                                      x.IndexColumns.First().FieldID == field.Id &&
                                                      x.IndexColumns.First().Ascending);

                if (index == null)
                {
                    var newIndex = new Index(modelRoot.Partition);
                    newIndex.ParentEntityID = field.Entity.Id;
                    newIndex.IndexType      = IndexTypeConstants.IsIndexed;
                    field.Entity.Indexes.Add(newIndex);

                    var newColumn = new IndexColumn(modelRoot.Partition);
                    newColumn.FieldID    = field.Id;
                    newColumn.IsInternal = true;
                    newIndex.IndexColumns.Add(newColumn);
                }
            }
        }
Example #3
0
        protected override void OnChildConfiguring(Microsoft.VisualStudio.Modeling.Diagrams.ShapeElement child, bool createdDuringViewFixup)
        {
            base.OnChildConfiguring(child, createdDuringViewFixup);

            try
            {
                if (!this.IsLoading)
                {
                    //Add a default field to entities
                    if (child.ModelElement is Entity)
                    {
                        var item  = child.ModelElement as Entity;
                        var model = item.nHydrateModel;
                        if (item.Fields.Count == 0)
                        {
                            var field = new Field(item.Partition)
                            {
                                DataType = DataTypeConstants.Int,
                                Identity = IdentityTypeConstants.Database,
                                Name     = "ID",
                            };
                            item.Fields.Add(field); //Add then set PK so it will trigger index code
                            field.IsPrimaryKey = true;
                        }

                        #region Pasting
                        //If there are invalid indexes then try to remap them
                        foreach (var index in item.Indexes.Where(x => x.FieldList.Any(z => z == null)))
                        {
                            foreach (var c in index.IndexColumns.Where(x => x.Field == null && x.FieldID != Guid.Empty))
                            {
                                var f = model.Entities.SelectMany(x => x.Fields).FirstOrDefault(x => x.Id == c.FieldID);
                                if (f != null)
                                {
                                    var f2 = item.Fields.FirstOrDefault(x => x.Name == f.Name);
                                    if (f2 != null)
                                    {
                                        c.FieldID = f2.Id;
                                    }
                                }
                            }
                        }

                        //Add a PK index if not one
                        if (!item.Indexes.Any(x => x.IndexType == IndexTypeConstants.PrimaryKey) && item.PrimaryKeyFields.Count > 0)
                        {
                            var index = new Index(item.Partition)
                            {
                                IndexType = IndexTypeConstants.PrimaryKey
                            };
                            item.Indexes.Add(index);
                            var loop = 0;
                            foreach (var field in item.PrimaryKeyFields)
                            {
                                var newIndexColumn = new IndexColumn(item.Partition);
                                index.IndexColumns.Add(newIndexColumn);
                                newIndexColumn.FieldID   = field.Id;
                                newIndexColumn.SortOrder = loop;
                                loop++;
                            }
                        }
                        #endregion
                    }
                    else if (child.ModelElement is View)
                    {
                        var item = child.ModelElement as View;
                        //if ((item.nHydrateModel.DiagramVisibility & VisibilityTypeConstants.View) != VisibilityTypeConstants.View)
                        //{
                        //  if (MessageBox.Show("This type of object cannot be created by dragging onto the diagram because it is not visualized on the diagram. You can change the 'DiagramVisibility' property of the model to visualize it. Otherwise you can only create this object type by using the model tree window.\n\nWould you like to toggle on visualization for this object?", "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes)
                        //  {
                        //    child.Delete();
                        //    return;
                        //  }
                        //  item.nHydrateModel.DiagramVisibility = (item.nHydrateModel.DiagramVisibility | VisibilityTypeConstants.View);
                        //}

                        if (item.Fields.Count == 0)
                        {
                            var field = new ViewField(item.Partition)
                            {
                                DataType = DataTypeConstants.Int,
                                Name     = "Field1",
                            };
                            item.Fields.Add(field);
                        }
                    }
                    else if (child.ModelElement is StoredProcedure)
                    {
                        var item = child.ModelElement as StoredProcedure;
                        //if ((item.nHydrateModel.DiagramVisibility & VisibilityTypeConstants.StoredProcedure) != VisibilityTypeConstants.StoredProcedure)
                        //{
                        //  if (MessageBox.Show("This type of object cannot be created by dragging onto the diagram because it is not visualized on the diagram. You can change the 'DiagramVisibility' property of the model to visualize it. Otherwise you can only create this object type by using the model tree window.\n\nWould you like to toggle on visualization for this object?", "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes)
                        //  {
                        //    child.Delete();
                        //    return;
                        //  }
                        //  item.nHydrateModel.DiagramVisibility = (item.nHydrateModel.DiagramVisibility | VisibilityTypeConstants.StoredProcedure);
                        //}

                        if (item.Fields.Count == 0)
                        {
                            var field = new StoredProcedureField(item.Partition)
                            {
                                DataType = DataTypeConstants.Int,
                                Name     = "Field1",
                            };
                            item.Fields.Add(field);
                        }
                        if (item.Parameters.Count == 0)
                        {
                            var field = new StoredProcedureParameter(item.Partition)
                            {
                                DataType = DataTypeConstants.Int,
                                Name     = "Parameter1",
                            };
                            item.Parameters.Add(field);
                        }
                    }
                    else if (child.ModelElement is Function)
                    {
                        var item = child.ModelElement as Function;
                        //if ((item.nHydrateModel.DiagramVisibility & VisibilityTypeConstants.Function) != VisibilityTypeConstants.Function)
                        //{
                        //  if (MessageBox.Show("This type of object cannot be created by dragging onto the diagram because it is not visualized on the diagram. You can change the 'DiagramVisibility' property of the model to visualize it. Otherwise you can only create this object type by using the model tree window.\n\nWould you like to toggle on visualization for this object?", "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes)
                        //  {
                        //    child.Delete();
                        //    return;
                        //  }
                        //  item.nHydrateModel.DiagramVisibility = (item.nHydrateModel.DiagramVisibility | VisibilityTypeConstants.Function);
                        //}

                        if (item.Fields.Count == 0)
                        {
                            var field = new FunctionField(item.Partition)
                            {
                                DataType = DataTypeConstants.Int,
                                Name     = "Field1",
                            };
                            item.Fields.Add(field);
                        }
                        if (item.Parameters.Count == 0)
                        {
                            var field = new FunctionParameter(item.Partition)
                            {
                                DataType = DataTypeConstants.Int,
                                Name     = "Parameter1",
                            };
                            item.Parameters.Add(field);
                        }
                    }

                    this.OnShapeConfiguring(new ModelElementEventArgs()
                    {
                        Shape = child
                    });
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #4
0
            protected override void OnValueChanged(FieldBase element, bool oldValue, bool newValue)
            {
                base.OnValueChanged(element, oldValue, newValue);

                try
                {
                    //Do not process if we are already doing something
                    //if (element.Store.TransactionManager.CurrentTransaction != null)
                    //{
                    //  if (element.Store.TransactionManager.CurrentTransaction.HasPendingChanges) return;
                    //}

                    if (element.Entity != null && element.Entity.nHydrateModel != null && !element.Entity.nHydrateModel.IsLoading)
                    {
                        //Processes Index list
                        if (element.IsPrimaryKey) //Must use real property since there is logic there
                        {
                            //This is a PK so determine if there is a key for this and add this field to a new or the existing index
                            var existing = element.Entity.Indexes.FirstOrDefault(x => x.IndexType == IndexTypeConstants.PrimaryKey);
                            if (existing == null)
                            {
                                //The PK index does not exist so create one
                                using (var transaction = element.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
                                {
                                    var newIndex = new Index(element.Partition);
                                    newIndex.ParentEntityID = element.Entity.Id;
                                    newIndex.Clustered      = true;
                                    element.Entity.Indexes.Add(newIndex);

                                    var newColumn = new IndexColumn(element.Partition);
                                    newColumn.FieldID = element.Id;
                                    newIndex.IndexColumns.Add(newColumn);
                                    newColumn.IsInternal = true;

                                    newIndex.IndexType = IndexTypeConstants.PrimaryKey; //Do this last

                                    //If use modules then add the PK to all modules that contain this entity
                                    if (element.Entity.nHydrateModel.UseModules)
                                    {
                                        foreach (var module in element.Modules)
                                        {
                                            element.Entity.nHydrateModel.IndexModules.Add(new IndexModule(element.Entity.nHydrateModel.Partition)
                                            {
                                                IndexID = newIndex.Id, ModuleId = module.Id
                                            });
                                        }
                                    }

                                    transaction.Commit();
                                }
                            }
                            else
                            {
                                //The PK does exist so add this field to it
                                using (var transaction = element.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
                                {
                                    if (existing.IndexColumns.Count(x => x.FieldID == element.Id) == 0)
                                    {
                                        existing.IndexType = IndexTypeConstants.User;
                                        var newColumn = new IndexColumn(element.Partition);
                                        newColumn.FieldID    = element.Id;
                                        newColumn.IsInternal = true;
                                        existing.IndexColumns.Add(newColumn);

                                        //Just in case there are invalid fields
                                        existing.IndexColumns.Remove(x => x.GetField() == null);

                                        existing.IndexType = IndexTypeConstants.PrimaryKey; //Do this last
                                        transaction.Commit();
                                    }
                                }
                            }

                            //Remove the IsIndex ones if exist
                            Func <Index, bool> where = x => x.IndexType == IndexTypeConstants.IsIndexed &&
                                                       x.IndexColumns.Count == 1 &&
                                                       x.IndexColumns.First().FieldID == element.Id &&
                                                       x.IndexType == IndexTypeConstants.IsIndexed;

                            element.Entity.Indexes.Where(where).ToList().ForEach(x => x.IndexType = IndexTypeConstants.User);
                            element.Entity.Indexes.Remove(where);
                        }
                        else //Remove Index
                        {
                            var existing = element.Entity.Indexes.FirstOrDefault(x => x.IndexType == IndexTypeConstants.PrimaryKey);
                            if (existing != null)
                            {
                                using (var transaction = element.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
                                {
                                    existing.IndexType = IndexTypeConstants.User;
                                    existing.IndexColumns.Remove(x => x.FieldID == element.Id);
                                    if (element.Entity.Fields.Count(x => x.IsPrimaryKey) == 0) //No more primary keys
                                    {
                                        element.Entity.Indexes.Remove(existing);
                                    }
                                    else
                                    {
                                        existing.IndexType = IndexTypeConstants.PrimaryKey;
                                    }

                                    //If use modules then add the PK to all modules that contain this entity
                                    if (element.Entity.nHydrateModel.UseModules && existing.FieldList.Count == 0)
                                    {
                                        foreach (var module in element.Modules)
                                        {
                                            element.Entity.nHydrateModel.IndexModules.Remove(x => (x.IndexID == existing.Id) && (x.ModuleId == module.Id));
                                        }
                                    }

                                    transaction.Commit();
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
Example #5
0
 public static Field GetField(this IndexColumn column)
 {
     return(column.Index.Entity.Fields.FirstOrDefault(x => x.Id == column.FieldID));
 }
        public static void LoadInitialIndexes(nHydrateModel modelRoot)
        {
            //Setup primary keys
            foreach (var entity in modelRoot.Entities)
            {
                if (entity.Indexes.Count(x => x.IndexType == IndexTypeConstants.PrimaryKey) == 0 && entity.PrimaryKeyFields.Count > 0)
                {
                    var newIndex = new Index(entity.Partition);
                    newIndex.ParentEntityID = entity.Id;
                    newIndex.IndexType = IndexTypeConstants.PrimaryKey;
                    newIndex.Clustered = true;
                    entity.Indexes.Add(newIndex);

                    foreach (var field in entity.PrimaryKeyFields)
                    {
                        var newColumn = new IndexColumn(field.Partition);
                        newColumn.FieldID = field.Id;
                        newColumn.IsInternal = true;
                        newIndex.IndexColumns.Add(newColumn);
                    }
                }
            }

            var allIndexedField = modelRoot.Entities.SelectMany(x => x.Fields).Where(x => x.IsIndexed && !x.IsPrimaryKey);
            var allIndexes = modelRoot.Entities.SelectMany(x => x.Indexes);
            foreach (var field in allIndexedField)
            {
                var index = allIndexes.FirstOrDefault(x =>
                                                      x.IndexColumns.Count == 1 &&
                                                      x.IndexColumns.First().FieldID == field.Id &&
                                                      x.IndexColumns.First().Ascending);

                if (index == null)
                {
                    var newIndex = new Index(modelRoot.Partition);
                    newIndex.ParentEntityID = field.Entity.Id;
                    newIndex.IndexType = IndexTypeConstants.IsIndexed;
                    field.Entity.Indexes.Add(newIndex);

                    var newColumn = new IndexColumn(modelRoot.Partition);
                    newColumn.FieldID = field.Id;
                    newColumn.IsInternal = true;
                    newIndex.IndexColumns.Add(newColumn);
                }
            }
        }
Example #7
0
        protected override void OnChildConfiguring(Microsoft.VisualStudio.Modeling.Diagrams.ShapeElement child, bool createdDuringViewFixup)
        {
            base.OnChildConfiguring(child, createdDuringViewFixup);

            try
            {
                if (!this.IsLoading)
                {
                    //Add a default field to entities
                    if (child.ModelElement is Entity)
                    {
                        var item  = child.ModelElement as Entity;
                        var model = item.nHydrateModel;
                        if (item.Fields.Count == 0)
                        {
                            var field = new Field(item.Partition)
                            {
                                DataType = DataTypeConstants.Int,
                                Identity = IdentityTypeConstants.Database,
                                Name     = "ID",
                            };
                            item.Fields.Add(field); //Add then set PK so it will trigger index code
                            field.IsPrimaryKey = true;
                        }

                        #region Pasting
                        //If there are invalid indexes then try to remap them
                        foreach (var index in item.Indexes.Where(x => x.FieldList.Any(z => z == null)))
                        {
                            foreach (var c in index.IndexColumns.Where(x => x.Field == null && x.FieldID != Guid.Empty))
                            {
                                var f = model.Entities.SelectMany(x => x.Fields).FirstOrDefault(x => x.Id == c.FieldID);
                                if (f != null)
                                {
                                    var f2 = item.Fields.FirstOrDefault(x => x.Name == f.Name);
                                    if (f2 != null)
                                    {
                                        c.FieldID = f2.Id;
                                    }
                                }
                            }
                        }

                        //Add a PK index if not one
                        if (!item.Indexes.Any(x => x.IndexType == IndexTypeConstants.PrimaryKey) && item.PrimaryKeyFields.Count > 0)
                        {
                            var index = new Index(item.Partition)
                            {
                                IndexType = IndexTypeConstants.PrimaryKey
                            };
                            item.Indexes.Add(index);
                            var loop = 0;
                            foreach (var field in item.PrimaryKeyFields)
                            {
                                var newIndexColumn = new IndexColumn(item.Partition);
                                index.IndexColumns.Add(newIndexColumn);
                                newIndexColumn.FieldID   = field.Id;
                                newIndexColumn.SortOrder = loop;
                                loop++;
                            }
                        }
                        #endregion
                    }
                    else if (child.ModelElement is View)
                    {
                        var item = child.ModelElement as View;
                        if (item.Fields.Count == 0)
                        {
                            var field = new ViewField(item.Partition)
                            {
                                DataType = DataTypeConstants.Int,
                                Name     = "Field1",
                            };
                            item.Fields.Add(field);
                        }
                    }

                    this.OnShapeConfiguring(new ModelElementEventArgs()
                    {
                        Shape = child
                    });
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #8
0
            protected override void OnValueChanged(FieldBase element, bool oldValue, bool newValue)
            {
                base.OnValueChanged(element, oldValue, newValue);

                try
                {
                    //Do not process if we are already doing something
                    //if (element.Store.TransactionManager.CurrentTransaction != null)
                    //{
                    //  if (element.Store.TransactionManager.CurrentTransaction.HasPendingChanges) return;
                    //}

                    if (element.Entity != null && element.Entity.nHydrateModel != null && !element.Entity.nHydrateModel.IsLoading)
                    {
                        //Processes Index list
                        if (element.IsPrimaryKey) //Must use real property since there is logic there
                        {
                            //This is a PK so determine if there is a key for this and add this field to a new or the existing index
                            var existing = element.Entity.Indexes.FirstOrDefault(x => x.IndexType == IndexTypeConstants.PrimaryKey);
                            if (existing == null)
                            {
                                //The PK index does not exist so create one
                                using (var transaction = element.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
                                {
                                    var newIndex = new Index(element.Partition);
                                    newIndex.ParentEntityID = element.Entity.Id;
                                    newIndex.Clustered = true;
                                    element.Entity.Indexes.Add(newIndex);

                                    var newColumn = new IndexColumn(element.Partition);
                                    newColumn.FieldID = element.Id;
                                    newIndex.IndexColumns.Add(newColumn);
                                    newColumn.IsInternal = true;

                                    newIndex.IndexType = IndexTypeConstants.PrimaryKey; //Do this last

                                    //If use modules then add the PK to all modules that contain this entity
                                    if (element.Entity.nHydrateModel.UseModules)
                                    {
                                        foreach (var module in element.Modules)
                                        {
                                            element.Entity.nHydrateModel.IndexModules.Add(new IndexModule(element.Entity.nHydrateModel.Partition) { IndexID = newIndex.Id, ModuleId = module.Id });
                                        }
                                    }

                                    transaction.Commit();
                                }
                            }
                            else
                            {
                                //The PK does exist so add this field to it
                                using (var transaction = element.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
                                {
                                    if (existing.IndexColumns.Count(x => x.FieldID == element.Id) == 0)
                                    {
                                        existing.IndexType = IndexTypeConstants.User;
                                        var newColumn = new IndexColumn(element.Partition);
                                        newColumn.FieldID = element.Id;
                                        newColumn.IsInternal = true;
                                        existing.IndexColumns.Add(newColumn);

                                        //Just in case there are invalid fields
                                        existing.IndexColumns.Remove(x => x.GetField() == null);

                                        existing.IndexType = IndexTypeConstants.PrimaryKey; //Do this last
                                        transaction.Commit();
                                    }
                                }
                            }

                            //Remove the IsIndex ones if exist
                            Func<Index, bool> where = x => x.IndexType == IndexTypeConstants.IsIndexed &&
                                x.IndexColumns.Count == 1 &&
                                x.IndexColumns.First().FieldID == element.Id &&
                                x.IndexType == IndexTypeConstants.IsIndexed;

                            element.Entity.Indexes.Where(where).ToList().ForEach(x => x.IndexType = IndexTypeConstants.User);
                            element.Entity.Indexes.Remove(where);

                        }
                        else //Remove Index
                        {
                            var existing = element.Entity.Indexes.FirstOrDefault(x => x.IndexType == IndexTypeConstants.PrimaryKey);
                            if (existing != null)
                            {
                                using (var transaction = element.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
                                {
                                    existing.IndexType = IndexTypeConstants.User;
                                    existing.IndexColumns.Remove(x => x.FieldID == element.Id);
                                    if (element.Entity.Fields.Count(x => x.IsPrimaryKey) == 0) //No more primary keys
                                        element.Entity.Indexes.Remove(existing);
                                    else
                                        existing.IndexType = IndexTypeConstants.PrimaryKey;

                                    //If use modules then add the PK to all modules that contain this entity
                                    if (element.Entity.nHydrateModel.UseModules && existing.FieldList.Count == 0)
                                    {
                                        foreach (var module in element.Modules)
                                        {
                                            element.Entity.nHydrateModel.IndexModules.Remove(x => (x.IndexID == existing.Id) && (x.ModuleId == module.Id));
                                        }
                                    }

                                    transaction.Commit();
                                }
                            }
                        }
                    }

                }
                catch (Exception ex)
                {
                    throw;
                }
            }
Example #9
0
            protected override void OnValueChanged(FieldBase element, bool oldValue, bool newValue)
            {
                base.OnValueChanged(element, oldValue, newValue);

                try
                {
                    if (element.Entity != null && element.Entity.nHydrateModel != null && !element.Entity.nHydrateModel.IsLoading)
                    {
                        //Processes Index list
                        if (newValue) //element.IsIndexed //Must use real property since there is logic there
                        {
                            //Add an Asc single field index
                            var existing = element.Entity.Indexes.FirstOrDefault(x => x.IndexColumns.Count == 1 && x.IndexColumns.First().FieldID == element.Id && x.IndexColumns.First().Ascending && x.IndexType == IndexTypeConstants.IsIndexed);
                            if (existing == null)
                            {
                                using (var transaction = element.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
                                {
                                    var newIndex = new Index(element.Partition);
                                    newIndex.ParentEntityID = element.Entity.Id;
                                    newIndex.IndexType = IndexTypeConstants.IsIndexed;
                                    newIndex.Clustered = false;
                                    element.Entity.Indexes.Add(newIndex);

                                    var newColumn = new IndexColumn(element.Partition);
                                    newColumn.FieldID = element.Id;
                                    newColumn.IsInternal = true;
                                    newIndex.IndexColumns.Add(newColumn);

                                    transaction.Commit();
                                }
                            }
                        }
                        else //Remove Index
                        {
                            var existingList = element.Entity.Indexes
                                .Where(x => x.IndexType == IndexTypeConstants.IsIndexed && x.IndexColumns.Count == 1 && x.IndexColumns.First().FieldID == element.Id && x.IndexType == IndexTypeConstants.IsIndexed)
                                .ToList();

                            using (var transaction = element.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
                            {
                                while (existingList.Count > 0)
                                {
                                    var item = existingList.First();
                                    item.IndexType = IndexTypeConstants.User;
                                    element.Entity.Indexes.Remove(item);
                                    existingList.Remove(item);
                                }
                                transaction.Commit();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw;
                }

            }
Example #10
0
        private static void LoadEntityIndexes(string folder, Entity entity)
        {
            XmlDocument document = null;
            var fileName = Path.Combine(folder, entity.Name + ".indexes.xml");
            if (!File.Exists(fileName)) return;
            try
            {
                document = new XmlDocument();
                document.Load(fileName);
            }
            catch (Exception ex)
            {
                //Do Nothing
                MessageBox.Show("The file '" + fileName + "' is not valid and could not be loaded!", "Load Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            foreach (XmlNode n in document.DocumentElement)
            {
                var id = XmlHelper.GetAttributeValue(n, "id", Guid.NewGuid());
                var newIndex = entity.Indexes.FirstOrDefault(x => x.Id == id);
                if (newIndex == null)
                {
                    newIndex = new Index(entity.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, id) });
                    entity.Indexes.Add(newIndex);
                }
                newIndex.Clustered = XmlHelper.GetAttributeValue(n, "clustered", newIndex.Clustered);
                newIndex.ImportedName = XmlHelper.GetAttributeValue(n, "importedname", newIndex.ImportedName);
                newIndex.IndexType = (IndexTypeConstants)XmlHelper.GetAttributeValue(n, "indextype", int.Parse(newIndex.IndexType.ToString("d")));
                newIndex.IsUnique = XmlHelper.GetAttributeValue(n, "isunique", newIndex.IsUnique);

                var indexColumnsNode = n.SelectSingleNode("indexcolumnset");
                if (indexColumnsNode != null)
                {
                    foreach (XmlNode m in indexColumnsNode.ChildNodes)
                    {
                        id = XmlHelper.GetAttributeValue(m, "id", Guid.NewGuid());
                        var newIndexColumn = newIndex.IndexColumns.FirstOrDefault(x => x.Id == id);
                        if (newIndexColumn == null)
                        {
                            newIndexColumn = new IndexColumn(entity.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, id) });
                            newIndex.IndexColumns.Add(newIndexColumn);
                        }
                        newIndexColumn.Ascending = XmlHelper.GetAttributeValue(m, "ascending", newIndexColumn.Ascending);
                        newIndexColumn.FieldID = XmlHelper.GetAttributeValue(m, "fieldid", newIndexColumn.FieldID);
                        newIndexColumn.SortOrder = XmlHelper.GetAttributeValue(m, "sortorder", newIndexColumn.SortOrder);
                        newIndexColumn.IsInternal = true;
                    }
                }
            }

        }
Example #11
0
        protected override void OnChildConfiguring(Microsoft.VisualStudio.Modeling.Diagrams.ShapeElement child, bool createdDuringViewFixup)
        {
            base.OnChildConfiguring(child, createdDuringViewFixup);

            try
            {
                if (!this.IsLoading)
                {
                    //Add a default field to entities
                    if (child.ModelElement is Entity)
                    {
                        var item = child.ModelElement as Entity;
                        var model = item.nHydrateModel;
                        if (item.Fields.Count == 0)
                        {
                            var field = new Field(item.Partition)
                                            {
                                                DataType = DataTypeConstants.Int,
                                                Identity = IdentityTypeConstants.Database,
                                                Name = "ID",
                                            };
                            item.Fields.Add(field); //Add then set PK so it will trigger index code
                            field.IsPrimaryKey = true;
                        }

                        #region Pasting
                        //If there are invalid indexes then try to remap them
                        foreach (var index in item.Indexes.Where(x => x.FieldList.Any(z => z == null)))
                        {
                            foreach (var c in index.IndexColumns.Where(x => x.Field == null && x.FieldID != Guid.Empty))
                            {
                                var f = model.Entities.SelectMany(x => x.Fields).FirstOrDefault(x => x.Id == c.FieldID);
                                if (f != null)
                                {
                                    var f2 = item.Fields.FirstOrDefault(x => x.Name == f.Name);
                                    if (f2 != null)
                                        c.FieldID = f2.Id;
                                }
                            }
                        }

                        //Add a PK index if not one
                        if (!item.Indexes.Any(x => x.IndexType == IndexTypeConstants.PrimaryKey) && item.PrimaryKeyFields.Count > 0)
                        {
                            var index = new Index(item.Partition) { IndexType = IndexTypeConstants.PrimaryKey };
                            item.Indexes.Add(index);
                            var loop = 0;
                            foreach (var field in item.PrimaryKeyFields)
                            {
                                var newIndexColumn = new IndexColumn(item.Partition);
                                index.IndexColumns.Add(newIndexColumn);
                                newIndexColumn.FieldID = field.Id;
                                newIndexColumn.SortOrder = loop;
                                loop++;
                            }
                        }
                        #endregion

                    }
                    else if (child.ModelElement is View)
                    {
                        var item = child.ModelElement as View;
                        //if ((item.nHydrateModel.DiagramVisibility & VisibilityTypeConstants.View) != VisibilityTypeConstants.View)
                        //{
                        //  if (MessageBox.Show("This type of object cannot be created by dragging onto the diagram because it is not visualized on the diagram. You can change the 'DiagramVisibility' property of the model to visualize it. Otherwise you can only create this object type by using the model tree window.\n\nWould you like to toggle on visualization for this object?", "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes)
                        //  {
                        //    child.Delete();
                        //    return;
                        //  }
                        //  item.nHydrateModel.DiagramVisibility = (item.nHydrateModel.DiagramVisibility | VisibilityTypeConstants.View);
                        //}

                        if (item.Fields.Count == 0)
                        {
                            var field = new ViewField(item.Partition)
                                            {
                                                DataType = DataTypeConstants.Int,
                                                Name = "Field1",
                                            };
                            item.Fields.Add(field);
                        }
                    }
                    else if (child.ModelElement is StoredProcedure)
                    {
                        var item = child.ModelElement as StoredProcedure;
                        //if ((item.nHydrateModel.DiagramVisibility & VisibilityTypeConstants.StoredProcedure) != VisibilityTypeConstants.StoredProcedure)
                        //{
                        //  if (MessageBox.Show("This type of object cannot be created by dragging onto the diagram because it is not visualized on the diagram. You can change the 'DiagramVisibility' property of the model to visualize it. Otherwise you can only create this object type by using the model tree window.\n\nWould you like to toggle on visualization for this object?", "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes)
                        //  {
                        //    child.Delete();
                        //    return;
                        //  }
                        //  item.nHydrateModel.DiagramVisibility = (item.nHydrateModel.DiagramVisibility | VisibilityTypeConstants.StoredProcedure);
                        //}

                        if (item.Fields.Count == 0)
                        {
                            var field = new StoredProcedureField(item.Partition)
                                            {
                                                DataType = DataTypeConstants.Int,
                                                Name = "Field1",
                                            };
                            item.Fields.Add(field);
                        }
                        if (item.Parameters.Count == 0)
                        {
                            var field = new StoredProcedureParameter(item.Partition)
                                            {
                                                DataType = DataTypeConstants.Int,
                                                Name = "Parameter1",
                                            };
                            item.Parameters.Add(field);
                        }
                    }
                    else if (child.ModelElement is Function)
                    {
                        var item = child.ModelElement as Function;
                        //if ((item.nHydrateModel.DiagramVisibility & VisibilityTypeConstants.Function) != VisibilityTypeConstants.Function)
                        //{
                        //  if (MessageBox.Show("This type of object cannot be created by dragging onto the diagram because it is not visualized on the diagram. You can change the 'DiagramVisibility' property of the model to visualize it. Otherwise you can only create this object type by using the model tree window.\n\nWould you like to toggle on visualization for this object?", "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes)
                        //  {
                        //    child.Delete();
                        //    return;
                        //  }
                        //  item.nHydrateModel.DiagramVisibility = (item.nHydrateModel.DiagramVisibility | VisibilityTypeConstants.Function);
                        //}

                        if (item.Fields.Count == 0)
                        {
                            var field = new FunctionField(item.Partition)
                                            {
                                                DataType = DataTypeConstants.Int,
                                                Name = "Field1",
                                            };
                            item.Fields.Add(field);
                        }
                        if (item.Parameters.Count == 0)
                        {
                            var field = new FunctionParameter(item.Partition)
                                            {
                                                DataType = DataTypeConstants.Int,
                                                Name = "Parameter1",
                                            };
                            item.Parameters.Add(field);
                        }
                    }

                    this.OnShapeConfiguring(new ModelElementEventArgs() { Shape = child });
                }

            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #12
0
        public static void ImportDatabase(nHydrate.Dsl.nHydrateModel model, Store store, Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram, nHydrate.DataImport.Database database, Module module)
        {

            try
            {
                //Find Stored procs with no loaded columns
                var noColumList = new List<string>();
                database.StoredProcList
                        .Where(x => (x.ImportState == DataImport.ImportStateConstants.Added || x.ImportState == DataImport.ImportStateConstants.Modified) && x.ColumnFailure)
                        .ToList()
                        .ForEach(x => noColumList.Add(x.Name));

                if (noColumList.Count > 0)
                {
                    MessageBox.Show("The output fields could not be determined for the following stored procedures. The fields collection of each will not be modified.\r\n\r\n" + string.Join("\r\n", noColumList.ToArray()), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            ((nHydrate.Dsl.nHydrateDiagram)diagram).IsLoading = true;
            model.IsLoading = true;
            var pkey = ProgressHelper.ProgressingStarted("Processing Import...", true);
            model.IsLoading = true;
            try
            {
                var addedEntities = new List<Entity>();
                var diagramEntities = model.Entities.ToList();
                var diagramStoredProcs = model.StoredProcedures.ToList();
                var diagramViews = model.Views.ToList();
                var diagramFunctions = model.Functions.ToList();
                using (var transaction = store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
                {
                    #region TEMP TEMP - RESET THE PARAMETERS AND FIELDS OF ALL NON-ENTITY OBJECTS - USED FOR DEBUGGING

                    //foreach (var entity in model.Entities)
                    //{
                    //  var table = database.EntityList.FirstOrDefault(x => x.Name == entity.Name);
                    //  if (table != null)
                    //  {
                    //    foreach (var field in entity.Fields)
                    //    {
                    //      var column = table.FieldList.FirstOrDefault(x => x.Name == field.Name);
                    //      if (column != null)
                    //      {
                    //        field.SortOrder = column.SortOrder;
                    //      }
                    //    }
                    //  }
                    //  entity.Fields.Sort((x, y) => (x.SortOrder < y.SortOrder ? -1 : 0));
                    //}

                    //var spList = database.StoredProcList.Where(x => x.ParameterList.Count(z => z.IsOutputParameter) > 0).ToList();
                    //foreach (var sp in spList)
                    //{
                    //  var newSP = model.StoredProcedures.FirstOrDefault(x => x.Name == sp.Name);
                    //  if (newSP != null)
                    //  {
                    //    foreach (var p in sp.ParameterList.Where(x => x.IsOutputParameter))
                    //    {
                    //      var newParameter = newSP.Parameters.FirstOrDefault(x => x.Name == p.Name);
                    //      if (newParameter != null)
                    //      {
                    //        newParameter.IsOutputParameter = true;
                    //      }
                    //    }
                    //  }
                    //}

                    //int paramCount = 0;
                    //int fieldCount = 0;
                    //foreach (var storedProc in database.StoredProcList.Where(x => x.ImportState == DataImport.ImportStateConstants.Added || x.ImportState == DataImport.ImportStateConstants.Modified))
                    //{
                    //  var newStoredProc = diagramStoredProcs.FirstOrDefault(x => x.Name.ToLower() == storedProc.Name.ToLower());
                    //  if (newStoredProc != null)
                    //  {
                    //    //Fields
                    //    foreach (var field in storedProc.FieldList)
                    //    {
                    //      var newField = newStoredProc.Fields.FirstOrDefault(x => x.Name == field.Name);
                    //      if (newField == null)
                    //      {
                    //        newField = new nHydrate.Dsl.StoredProcedureField(model.Partition);
                    //        newStoredProc.Fields.Add(newField);
                    //        newField.Name = field.Name;
                    //        newField.Length = field.Length;
                    //        newField.Nullable = field.Nullable;
                    //        newField.DataType = (DataTypeConstants)Enum.Parse(typeof(DataTypeConstants), field.DataType.ToString());
                    //        newField.Default = field.DefaultValue;
                    //        newField.Scale = field.Scale;
                    //        fieldCount++;
                    //      }

                    //    }

                    //    //Parameters
                    //    foreach (var parameter in storedProc.ParameterList)
                    //    {
                    //      var newParameter = newStoredProc.Parameters.FirstOrDefault(x => x.Name == parameter.Name);
                    //      if (newParameter == null)
                    //      {
                    //        newParameter = new nHydrate.Dsl.StoredProcedureParameter(model.Partition);
                    //        newStoredProc.Parameters.Add(newParameter);
                    //        newParameter.Name = parameter.Name;
                    //        newParameter.SortOrder = parameter.SortOrder;
                    //        newParameter.Length = parameter.Length;
                    //        newParameter.Nullable = parameter.Nullable;
                    //        newParameter.DataType = (DataTypeConstants)Enum.Parse(typeof(DataTypeConstants), parameter.DataType.ToString());
                    //        newParameter.Default = parameter.DefaultValue;
                    //        newParameter.Scale = parameter.Scale;
                    //        newParameter.IsOutputParameter = parameter.IsOutputParameter;
                    //        paramCount++;
                    //      }

                    //    }
                    //  }
                    //}

                    //foreach (var storedProc in database.StoredProcList)
                    //{
                    //  var newStoredProc = diagramStoredProcs.FirstOrDefault(x => x.Name.ToLower() == storedProc.Name.ToLower());
                    //  if (newStoredProc != null)
                    //  {
                    //    foreach (var field in storedProc.FieldList)
                    //    {
                    //      var newField = newStoredProc.Fields.FirstOrDefault(x => x.Name.ToLower() == field.Name.ToLower());
                    //      if (newField != null) newField.Nullable = field.Nullable;
                    //    }

                    //    foreach (var parameter in storedProc.ParameterList)
                    //    {
                    //      var newParameter = newStoredProc.Parameters.FirstOrDefault(x => x.Name.ToLower() == parameter.Name.ToLower());
                    //      if (newParameter != null) newParameter.Nullable = parameter.Nullable;
                    //    }
                    //  }
                    //}

                    //foreach (var view in database.ViewList)
                    //{
                    //  var newView = diagramViews.FirstOrDefault(x => x.Name.ToLower() == view.Name.ToLower());
                    //  if (newView != null)
                    //  {
                    //    foreach (var field in view.FieldList)
                    //    {
                    //      var newField = newView.Fields.FirstOrDefault(x => x.Name.ToLower() == field.Name.ToLower());
                    //      if (newField != null) newField.Nullable = field.Nullable;
                    //    }
                    //  }
                    //}

                    //foreach (var function in database.FunctionList)
                    //{
                    //  var newFunction = diagramFunctions.FirstOrDefault(x => x.Name.ToLower() == function.Name.ToLower());
                    //  if (newFunction != null)
                    //  {
                    //    foreach (var field in function.FieldList)
                    //    {
                    //      var newField = newFunction.Fields.FirstOrDefault(x => x.Name.ToLower() == field.Name.ToLower());
                    //      if (newField != null) newField.Nullable = field.Nullable;
                    //    }

                    //    foreach (var parameter in function.ParameterList)
                    //    {
                    //      var newParameter = newFunction.Parameters.FirstOrDefault(x => x.Name.ToLower() == parameter.Name.ToLower());
                    //      if (newParameter != null) newParameter.Nullable = parameter.Nullable;
                    //    }
                    //  }
                    //}

                    //foreach (var index in database.IndexList.Where(x => x.FieldList.Count == 1 && !x.FieldList.First().IsDescending))
                    //{
                    //  var entity = model.Entities.FirstOrDefault(x => x.Name == index.TableName);
                    //  if (entity != null)
                    //  {
                    //    var field = entity.Fields.FirstOrDefault(x => x.Name == index.FieldList.First().Name);
                    //    if (field != null)
                    //    {
                    //      field.IsIndexed = true;
                    //    }
                    //  }
                    //}

                    //transaction.Commit();
                    //return;

                    #endregion

                    #region Load Entities

                    #region Merge Module
                    foreach (var item in database.EntityList.Where(x => x.ImportState == DataImport.ImportStateConstants.Merge))
                    {
                        //Add module if necessary
                        var modelItem = diagramEntities.FirstOrDefault(x => x.Name.ToLower() == item.Name.ToLower());
                        if (module != null && !modelItem.Modules.Contains(module))
                        {
                            modelItem.Modules.Add(module);
                        }

                        foreach (var field in item.FieldList)
                        {
                            var newField = modelItem.Fields.FirstOrDefault(x => x.Name.ToLower() == field.Name.ToLower());

                            //Add module if necessary
                            if (module != null && newField != null && !newField.Modules.Contains(module))
                            {
                                newField.Modules.Add(module);
                            }
                        }

                    }
                    #endregion

                    var addedChangedEntities = database.EntityList.Where(x => x.ImportState == DataImport.ImportStateConstants.Added || x.ImportState == DataImport.ImportStateConstants.Modified).ToList();

                    #region Entities

                    foreach (var entity in addedChangedEntities)
                    {
                        var newEntity = diagramEntities.FirstOrDefault(x => x.Id == entity.ID);
                        if (newEntity == null) newEntity = diagramEntities.FirstOrDefault(x => x.Name.ToLower() == entity.Name.ToLower());
                        if (newEntity == null)
                        {
                            newEntity = new Entity(model.Partition) { Name = entity.Name };
                            model.Entities.Add(newEntity);
                            addedEntities.Add(newEntity);

                            //Correct for invalid identifiers
                            //if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newEntity.Name) && !nHydrate.Dsl.ValidationHelper.IsReservedWord(newEntity.Name))
                            if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newEntity.Name))
                            {
                                newEntity.CodeFacade = nHydrate.Dsl.ValidationHelper.MakeCodeIdentifer(newEntity.Name, string.Empty);
                            }
                        }
                        newEntity.AllowCreateAudit = entity.AllowCreateAudit;
                        newEntity.AllowModifyAudit = entity.AllowModifyAudit;
                        newEntity.AllowTimestamp = entity.AllowTimestamp;
                        newEntity.IsTenant = entity.IsTenant;
                        newEntity.Name = entity.Name;
                        newEntity.Schema = entity.Schema;

                        //Add module if necessary
                        if (module != null && !newEntity.Modules.Contains(module))
                        {
                            newEntity.Modules.Add(module);
                        }

                        PopulateFields(model, module, entity, newEntity);

                        //Order columns by database
                        //newEntity.Fields.Sort((x, y) => x.Name.CompareTo(y.Name));
                        newEntity.Fields.Sort((x, y) => (x.SortOrder < y.SortOrder ? -1 : 0));
                    }

                    #endregion

                    //Find all fields in the removed entities
                    var removalFieldIdList = model.Entities
                        .Where(x => database.EntityList
                            .Where(z => z.ImportState == DataImport.ImportStateConstants.Deleted)
                            .Select(a => a.Name)
                            .ToList()
                            .Contains(x.Name)).ToList()
                            .SelectMany(x => x.Fields).Select(x => x.Id);

                    ////Remove these fields from the relation field map collection
                    //model.RelationFields.Remove(x => removalFieldIdList.Contains(x.SourceFieldId) || removalFieldIdList.Contains(x.TargetFieldId));

                    //Remove the ones that need to be remove
                    model.Entities.Remove(x => database.EntityList.Where(z => z.ImportState == DataImport.ImportStateConstants.Deleted).Select(a => a.Name).ToList().Contains(x.Name));

                    #endregion

                    #region Load Relations
                    if (!database.IgnoreRelations)
                    {
                        var allRelationElementList = store.CurrentContext.Partitions.First().Value.ElementDirectory.AllElements
                            .ToList()
                            .Where(x => x is EntityHasEntities)
                            .ToList()
                            .Cast<EntityHasEntities>()
                            .ToList();

                        foreach (var entity in database.EntityList)
                        {
                            foreach (var relation in entity.RelationshipList)
                            {
                                var isNewConnection = false;
                                var connection = allRelationElementList.FirstOrDefault(x => x.ImportData == relation.ImportData);

                                //Now verify that this is the table has not been renamed
                                if (connection != null)
                                {
                                    //If the table names no longer match then create a new relation
                                    if (string.Compare(connection.ChildEntity.Name, relation.TargetEntity.Name, true) != 0 ||
                                        string.Compare(connection.ParentEntity.Name, relation.SourceEntity.Name, true) != 0)
                                    {
                                        connection.ImportData = string.Empty;
                                        connection = null;
                                    }
                                }

                                if (connection == null)
                                {
                                    //try to find this relation by table/fields/role
                                    connection = allRelationElementList.FirstOrDefault(x => x.GetCorePropertiesHash() == relation.CorePropertiesHash);
                                }
                                var parent = model.Entities.FirstOrDefault(x => x.Name == relation.SourceEntity.Name);
                                var child = model.Entities.FirstOrDefault(x => x.Name == relation.TargetEntity.Name);
                                if (connection == null)
                                {
                                    var existingRelation = diagram.NestedChildShapes.FirstOrDefault(x => x.Id == relation.ID);
                                    if (existingRelation == null)
                                    {
                                        if (child != null && parent != null)
                                        {

                                            //var currentList = store.CurrentContext.Partitions.First().Value.ElementDirectory.AllElements.ToList();
                                            //parent.ChildEntities.Add(child);
                                            //var updatedList = store.CurrentContext.Partitions.First().Value.ElementDirectory.AllElements.ToList();
                                            //var last = updatedList.Last();
                                            //updatedList.RemoveAll(x => currentList.Contains(x));
                                            //connection = updatedList.First() as EntityHasEntities;
                                            //if (connection != last) System.Diagnostics.Debug.Write("");

                                            parent.ChildEntities.Add(child);
                                            connection = store.CurrentContext.Partitions.First().Value.ElementDirectory.AllElements.Last() as EntityHasEntities;

                                            isNewConnection = true;
                                            connection.ImportData = relation.ImportData;
                                        }
                                    }
                                } //Relation does not exist

                                //Add the relation fields
                                if (parent != null && child != null)
                                {
                                    foreach (var ritem in relation.RelationshipColumnList)
                                    {
                                        var parentField = parent.Fields.FirstOrDefault(x => x.Name == ritem.ParentField.Name);
                                        var childField = child.Fields.FirstOrDefault(x => x.Name == ritem.ChildField.Name);
                                        if (parentField != null && childField != null)
                                        {
                                            //Do not import the role name again.
                                            if (isNewConnection)
                                            {
                                                connection.RoleName = relation.RoleName;
                                                connection.ImportedConstraintName = relation.ConstraintName;
                                            }

                                            var currentRelationField = model.RelationFields.FirstOrDefault(x =>
                                                x.SourceFieldId == parentField.Id &&
                                                x.TargetFieldId == childField.Id &&
                                                x.RelationID == connection.Id);

                                            //Only add if not there already
                                            if (currentRelationField == null)
                                            {
                                                model.RelationFields.Add(
                                                    new RelationField(model.Partition)
                                                    {
                                                        SourceFieldId = parentField.Id,
                                                        TargetFieldId = childField.Id,
                                                        RelationID = connection.Id,
                                                    }
                                                    );
                                            }
                                        }
                                    } //Relation Columns
                                }

                            }
                        }
                    }
                    #endregion

                    #region Process Indexes

                    //Only get the single column indexes ascending
                    var isIndexedList = database.IndexList.Where(x => x.FieldList.Count == 1 && !x.FieldList.First().IsDescending).ToList();
                    var allIndexList = database.IndexList.Where(x => addedChangedEntities.Select(z => z.Name.ToLower()).Contains(x.TableName.ToLower())).ToList();

                    //Delete existing indexes by name. These will be recreated.
                    foreach (var index in allIndexList)
                    {
                        var existing = model.Entities.SelectMany(x => x.Indexes).FirstOrDefault(x => x.ImportedName == index.IndexName);
                        if (existing != null)
                        {
                            existing.Delete();
                        }
                    }

                    //Delete existing IsIndexed indexes with no import names as they will be recreated
                    var existingIsIndexedList = model.Entities.Where(x => addedChangedEntities.Select(z => z.Name.ToLower()).Contains(x.Name.ToLower())).SelectMany(x => x.Indexes).Where(x => x.IsIndexedType).ToList();
                    foreach (var index in isIndexedList)
                    {
                        foreach (var existing in existingIsIndexedList)
                        {
                            if (index.IsMatch(existing))
                                existing.Delete();
                        }
                    }

                    //Create all indexes
                    foreach (var index in allIndexList)
                    {
                        var entity = model.Entities.FirstOrDefault(x => x.Name == index.TableName);
                        if (entity != null)
                        {
                            var realFields = entity.Fields.Where(x => index.FieldList.Select(z => z.Name).Contains(x.Name)).ToList();
                            if (realFields.Count > 0)
                            {
                                //Try to get the PK if one exists
                                var isNew = true;
                                Index newIndex = null;
                                if (index.IsPrimaryKey)
                                {
                                    newIndex = entity.Indexes.FirstOrDefault(x => x.IndexType == IndexTypeConstants.PrimaryKey);
                                    if (newIndex != null)
                                    {
                                        isNew = false;
                                        newIndex.IndexColumns.Clear();
                                    }
                                }

                                //Create an index
                                if (newIndex == null)
                                    newIndex = new Index(entity.Partition);

                                newIndex.ParentEntityID = entity.Id;
                                newIndex.ImportedName = index.IndexName;
                                newIndex.Clustered = index.Clustered;
                                newIndex.IsUnique = index.IsUnique;

                                if (index.IsPrimaryKey)
                                    newIndex.IndexType = IndexTypeConstants.PrimaryKey;
                                else if (isIndexedList.Contains(index))
                                    newIndex.IndexType = IndexTypeConstants.IsIndexed;
                                else
                                    newIndex.IndexType = IndexTypeConstants.User;

                                if (isNew)
                                    entity.Indexes.Add(newIndex);

                                foreach (var ic in index.FieldList)
                                {
                                    var field = realFields.FirstOrDefault(x => x.Name == ic.Name);
                                    if (field != null)
                                    {
                                        var newIndexColumn = new IndexColumn(entity.Partition);
                                        newIndexColumn.Ascending = !ic.IsDescending;
                                        newIndexColumn.FieldID = field.Id;
                                        newIndexColumn.IsInternal = true;
                                        newIndexColumn.SortOrder = ic.OrderIndex;
                                        newIndex.IndexColumns.Add(newIndexColumn);
                                    }
                                }
                            }

                        }
                    }

                    //Create the special IsIndexed settings
                    //This will not create a new index since it was created above
                    foreach (var index in isIndexedList)
                    {
                        var entity = model.Entities.FirstOrDefault(x => x.Name == index.TableName);
                        if ((entity != null) && addedChangedEntities.Select(z => z.Name.ToLower()).Contains(entity.Name.ToLower()))
                        {
                            var field = entity.Fields.FirstOrDefault(x => x.Name == index.FieldList.First().Name);
                            if (field != null)
                            {
                                field.IsIndexed = true;
                            }
                        }
                    }

                    #endregion

                    #region Add Stored Procedures

                    #region Merge Module
                    foreach (var item in database.StoredProcList.Where(x => x.ImportState == DataImport.ImportStateConstants.Merge))
                    {
                        //Add module if necessary
                        var modelItem = diagramStoredProcs.FirstOrDefault(x => x.Name.ToLower() == item.Name.ToLower());
                        if (module != null && !modelItem.Modules.Contains(module))
                        {
                            modelItem.Modules.Add(module);
                        }
                    }
                    #endregion

                    foreach (var storedProc in database.StoredProcList.Where(x => x.ImportState == DataImport.ImportStateConstants.Added || x.ImportState == DataImport.ImportStateConstants.Modified))
                    {
                        var newStoredProc = diagramStoredProcs.Where(x => x.Id == storedProc.ID).FirstOrDefault();
                        if (newStoredProc == null) newStoredProc = diagramStoredProcs.FirstOrDefault(x => x.Name.ToLower() == storedProc.Name.ToLower());
                        if (newStoredProc == null)
                        {
                            newStoredProc = new StoredProcedure(model.Partition) { Name = storedProc.Name };
                            model.StoredProcedures.Add(newStoredProc);

                            //Correct for invalid identifiers
                            //if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newStoredProc.Name) && !nHydrate.Dsl.ValidationHelper.IsReservedWord(newStoredProc.Name))
                            if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newStoredProc.Name))
                            {
                                newStoredProc.CodeFacade = nHydrate.Dsl.ValidationHelper.MakeCodeIdentifer(newStoredProc.Name, string.Empty);
                            }
                        }
                        newStoredProc.Name = storedProc.Name;
                        newStoredProc.DatabaseObjectName = newStoredProc.Name; //Ensures the "gen_" prefix is not prepended

                        //Add module if necessary
                        if (module != null && !newStoredProc.Modules.Contains(module))
                        {
                            newStoredProc.Modules.Add(module);
                        }

                        newStoredProc.Schema = storedProc.Schema;
                        newStoredProc.SQL = storedProc.SQL;

                        PopulateFields(model, storedProc, newStoredProc);
                        PopulateParameters(model, storedProc, newStoredProc);
                    }

                    //Remove the ones that need to be remove
                    model.StoredProcedures.Remove(x => database.StoredProcList.Where(z => z.ImportState == DataImport.ImportStateConstants.Deleted).Select(a => a.Name).ToList().Contains(x.Name));

                    #endregion

                    #region Add Views

                    #region Merge Module
                    foreach (var item in database.ViewList.Where(x => x.ImportState == DataImport.ImportStateConstants.Merge))
                    {
                        //Add module if necessary
                        var modelItem = diagramViews.FirstOrDefault(x => x.Name.ToLower() == item.Name.ToLower());
                        if (module != null && !modelItem.Modules.Contains(module))
                        {
                            modelItem.Modules.Add(module);
                        }
                    }
                    #endregion

                    foreach (var view in database.ViewList.Where(x => x.ImportState == DataImport.ImportStateConstants.Added || x.ImportState == DataImport.ImportStateConstants.Modified))
                    {
                        var newView = diagramViews.Where(x => x.Id == view.ID).FirstOrDefault();
                        if (newView == null) newView = diagramViews.FirstOrDefault(x => x.Name.ToLower() == view.Name.ToLower());
                        if (newView == null)
                        {
                            newView = new nHydrate.Dsl.View(model.Partition) { Name = view.Name };
                            model.Views.Add(newView);

                            //Correct for invalid identifiers
                            //if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newView.Name) && !nHydrate.Dsl.ValidationHelper.IsReservedWord(newView.Name))
                            if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newView.Name))
                            {
                                newView.CodeFacade = nHydrate.Dsl.ValidationHelper.MakeCodeIdentifer(newView.Name, string.Empty);
                            }
                        }
                        newView.Name = view.Name;

                        //Add module if necessary
                        if (module != null && !newView.Modules.Contains(module))
                        {
                            newView.Modules.Add(module);
                        }

                        newView.Schema = view.Schema;
                        newView.SQL = view.SQL;

                        PopulateFields(model, view, newView);

                    }

                    //Remove the ones that need to be remove
                    model.Views.Remove(x => database.ViewList.Where(z => z.ImportState == DataImport.ImportStateConstants.Deleted).Select(a => a.Name).ToList().Contains(x.Name));

                    #endregion

                    #region Add Functions

                    #region Merge Module
                    foreach (var item in database.FunctionList.Where(x => x.ImportState == DataImport.ImportStateConstants.Merge))
                    {
                        //Add module if necessary
                        var modelItem = diagramFunctions.FirstOrDefault(x => x.Name.ToLower() == item.Name.ToLower());
                        if (module != null && !modelItem.Modules.Contains(module))
                        {
                            modelItem.Modules.Add(module);
                        }
                    }
                    #endregion

                    foreach (var function in database.FunctionList.Where(x => x.ImportState == DataImport.ImportStateConstants.Added || x.ImportState == DataImport.ImportStateConstants.Modified))
                    {
                        var newFunction = diagramFunctions.Where(x => x.Id == function.ID).FirstOrDefault();
                        if (newFunction == null) newFunction = diagramFunctions.FirstOrDefault(x => x.Name.ToLower() == function.Name.ToLower());
                        if (newFunction == null)
                        {
                            newFunction = new Function(model.Partition) { Name = function.Name };
                            model.Functions.Add(newFunction);

                            //Correct for invalid identifiers
                            if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newFunction.Name))
                            {
                                newFunction.CodeFacade = nHydrate.Dsl.ValidationHelper.MakeCodeIdentifer(newFunction.Name, string.Empty);
                            }
                        }
                        newFunction.Name = function.Name;
                        newFunction.ReturnVariable = function.ReturnVariable;

                        newFunction.IsTable = function.IsTable;

                        //Add module if necessary
                        if (module != null && !newFunction.Modules.Contains(module))
                        {
                            newFunction.Modules.Add(module);
                        }

                        newFunction.Schema = function.Schema;
                        newFunction.SQL = function.SQL;

                        PopulateFields(model, function, newFunction);
                        PopulateParameters(model, function, newFunction);

                    }

                    //Remove the ones that need to be remove
                    model.Functions.Remove(x => database.FunctionList.Where(z => z.ImportState == DataImport.ImportStateConstants.Deleted).Select(a => a.Name).ToList().Contains(x.Name));
                    #endregion

                    //Reset Precedense if necessary
                    model.StoredProcedures.Where(x => x.PrecedenceOrder == 0).ToList().ForEach(x => x.PrecedenceOrder = ++model.MaxPrecedenceOrder);
                    model.Views.Where(x => x.PrecedenceOrder == 0).ToList().ForEach(x => x.PrecedenceOrder = ++model.MaxPrecedenceOrder);
                    model.Functions.Where(x => x.PrecedenceOrder == 0).ToList().ForEach(x => x.PrecedenceOrder = ++model.MaxPrecedenceOrder);

                    transaction.Commit();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                model.IsLoading = false;

                ProgressHelper.ProgressingComplete(pkey);
                ((nHydrate.Dsl.nHydrateDiagram)diagram).IsLoading = false;
                model.IsLoading = false;
            }

        }