Inheritance: nHydrate.Dsl.IContainerParent, nHydrate.Dsl.IField
Ejemplo n.º 1
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;
            }
        }
Ejemplo n.º 2
0
        private static void LoadFromDisk(IEnumerable<StoredProcedure> list, nHydrateModel model, string rootFolder, Microsoft.VisualStudio.Modeling.Store store)
        {
            var folder = Path.Combine(rootFolder, FOLDER_SP);
            if (!Directory.Exists(folder)) return;

            #region Load other parameter/field information
            var fList = Directory.GetFiles(folder, "*.configuration.xml");
            foreach (var f in fList)
            {
                var document = new XmlDocument();
                try
                {
                    document.Load(f);
                }
                catch (Exception ex)
                {
                    //Do Nothing
                    MessageBox.Show("The file '" + f + "' is not valid and could not be loaded!", "Load Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                var fi = new FileInfo(f);
                var name = fi.Name.Substring(0, fi.Name.Length - ".configuration.xml".Length).ToLower();
                var itemID = XmlHelper.GetAttributeValue(document.DocumentElement, "id", Guid.Empty);
                var item = list.FirstOrDefault(x => x.Id == itemID);
                if (item == null)
                {
                    item = new StoredProcedure(model.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, XmlHelper.GetAttributeValue(document.DocumentElement, "id", Guid.NewGuid())) });
                    model.StoredProcedures.Add(item);
                }

                System.Windows.Forms.Application.DoEvents();

                item.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                item.Name = XmlHelper.GetAttributeValue(document.DocumentElement, "name", item.Name);
                item.PrecedenceOrder = XmlHelper.GetAttributeValue(document.DocumentElement, "precedenceorder", item.PrecedenceOrder);
                item.IsGenerated = XmlHelper.GetAttributeValue(document.DocumentElement, "isgenerated", item.IsGenerated);
                item.CodeFacade = XmlHelper.GetAttributeValue(document.DocumentElement, "codefacade", item.CodeFacade);
                item.Schema = XmlHelper.GetAttributeValue(document.DocumentElement, "schema", item.Schema);
                item.DatabaseObjectName = XmlHelper.GetAttributeValue(document.DocumentElement, "databaseobjectname", item.DatabaseObjectName);
                item.IsExisting = XmlHelper.GetAttributeValue(document.DocumentElement, "isexisting", item.IsExisting);
                item.GeneratesDoubleDerived = XmlHelper.GetAttributeValue(document.DocumentElement, "generatesdoublederived", item.GeneratesDoubleDerived);
                item.Summary = XmlHelper.GetNodeValue(document.DocumentElement, "summary", item.Summary);
                item.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);

                //Fields
                var fieldsNodes = document.DocumentElement.SelectSingleNode("//fieldset");
                if (fieldsNodes != null)
                {
                    var nameList = new List<string>();
                    foreach (XmlNode n in fieldsNodes.ChildNodes)
                    {
                        var subItemID = XmlHelper.GetAttributeValue(n, "id", Guid.Empty);
                        var field = item.Fields.FirstOrDefault(x => x.Id == subItemID);
                        if (field == null)
                        {
                            field = new StoredProcedureField(item.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, XmlHelper.GetAttributeValue(n, "id", Guid.NewGuid())) });
                            item.Fields.Add(field);
                        }

                        field.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                        field.Name = XmlHelper.GetAttributeValue(n, "name", field.Name);
                        field.CodeFacade = XmlHelper.GetAttributeValue(n, "codefacade", field.CodeFacade);
                        nameList.Add(field.Name.ToLower());
                        field.Nullable = XmlHelper.GetAttributeValue(n, "nullable", field.Nullable);
                        var dtv = XmlHelper.GetAttributeValue(n, "datatype", field.DataType.ToString());
                        DataTypeConstants dt;
                        if (Enum.TryParse<DataTypeConstants>(dtv, true, out dt))
                            field.DataType = dt;
                        field.Default = XmlHelper.GetAttributeValue(n, "default", field.Default);
                        field.IsGenerated = XmlHelper.GetAttributeValue(n, "isgenerated", field.IsGenerated);
                        field.Length = XmlHelper.GetAttributeValue(n, "length", field.Length);
                        field.Scale = XmlHelper.GetAttributeValue(n, "scale", field.Scale);
                        field.Summary = XmlHelper.GetNodeValue(n, "summary", field.Summary);
                        field.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                    }
                    if (item.Fields.Remove(x => !nameList.Contains(x.Name.ToLower())) > 0)
                        item.nHydrateModel.IsDirty = true;
                }

                //Parameters
                var parametersNodes = document.DocumentElement.SelectSingleNode("//parameterset");
                if (parametersNodes != null)
                {
                    var nameList = new List<string>();
                    foreach (XmlNode n in parametersNodes.ChildNodes)
                    {
                        var subItemID = XmlHelper.GetAttributeValue(n, "id", Guid.Empty);
                        var parameter = item.Parameters.FirstOrDefault(x => x.Id == subItemID);
                        if (parameter == null)
                        {
                            parameter = new StoredProcedureParameter(item.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, XmlHelper.GetAttributeValue(n, "id", Guid.NewGuid())) });
                            item.Parameters.Add(parameter);
                        }

                        parameter.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                        parameter.Name = XmlHelper.GetAttributeValue(n, "name", parameter.Name);
                        parameter.CodeFacade = XmlHelper.GetAttributeValue(n, "codefacade", parameter.CodeFacade);
                        parameter.IsOutputParameter = XmlHelper.GetAttributeValue(n, "isoutput", parameter.IsOutputParameter);
                        nameList.Add(parameter.Name.ToLower());
                        parameter.Nullable = XmlHelper.GetAttributeValue(n, "nullable", parameter.Nullable);
                        var dtv = XmlHelper.GetAttributeValue(n, "datatype", parameter.DataType.ToString());
                        DataTypeConstants dt;
                        if (Enum.TryParse<DataTypeConstants>(dtv, true, out dt))
                            parameter.DataType = dt;
                        parameter.Default = XmlHelper.GetAttributeValue(n, "default", parameter.Default);
                        parameter.IsGenerated = XmlHelper.GetAttributeValue(n, "isgenerated", parameter.IsGenerated);
                        parameter.Length = XmlHelper.GetAttributeValue(n, "length", parameter.Length);
                        parameter.Scale = XmlHelper.GetAttributeValue(n, "scale", parameter.Scale);
                        parameter.Summary = XmlHelper.GetNodeValue(n, "summary", parameter.Summary);
                        parameter.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                    }
                    if (item.Parameters.Remove(x => !nameList.Contains(x.Name.ToLower())) > 0)
                        item.nHydrateModel.IsDirty = true;
                }

                LoadModules(folder, item);

            }
            #endregion

            #region Load SQL
            fList = Directory.GetFiles(folder, "*.sql");
            foreach (var f in fList)
            {
                var fi = new FileInfo(f);
                if (fi.Name.ToLower().EndsWith(".sql"))
                {
                    var name = fi.Name.Substring(0, fi.Name.Length - ".sql".Length).ToLower();
                    var item = list.FirstOrDefault(x => x.Name.ToLower() == name);
                    if (item != null)
                    {
                        item.SQL = File.ReadAllText(f);
                        System.Windows.Forms.Application.DoEvents();
                    }
                }
            }
            #endregion

        }
Ejemplo n.º 3
0
        public static void PopulateFields(nHydrate.Dsl.nHydrateModel model, DataImport.StoredProc storedProc, StoredProcedure newStoredProc)
        {
            if (storedProc.ColumnFailure) return;

            //Fields
            //newStoredProc.Fields.Clear();
            foreach (var field in storedProc.FieldList)
            {
                var newField = newStoredProc.Fields.FirstOrDefault(x => x.Name.ToLower() == field.Name.ToLower());
                if (newField == null)
                {
                    newField = new nHydrate.Dsl.StoredProcedureField(model.Partition);
                    newField.Name = field.Name;
                    newStoredProc.Fields.Add(newField);

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

                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;
            }
            //Remove the fields that need to be remove
            newStoredProc.Fields.Remove(x => !storedProc.FieldList.Select(a => a.Name.ToLower()).ToList().Contains(x.Name.ToLower()));
        }
Ejemplo n.º 4
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;
            }
        }
Ejemplo n.º 5
0
        public static void ImportLegacyModel(nHydrateModel model, Store store, nHydrateDiagram diagram, string legacyFileName)
        {
            diagram.IsLoading = true;
            model.IsLoading = true;
            try
            {
                var addedElements = new List<ModelElement>();
                using (var transaction = store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
                {
                    //The loading assemblies have changed names, so we must manually intervene
                    var newFile = legacyFileName + ".converting";
                    nHydrate.Generator.nHydrateGeneratorProject project = null;
                    try
                    {
                        File.Copy(legacyFileName, newFile);
                        var fileText = File.ReadAllText(newFile);
                        fileText = fileText.Replace("Widgetsphere.Generator.", "nHydrate.Generator.");
                        fileText = fileText.Replace("WidgetsphereGeneratorProject", "nHydrateGeneratorProject");
                        File.WriteAllText(newFile, fileText);
                        System.Threading.Thread.Sleep(500);
                        project = nHydrate.Generator.Common.GeneratorFramework.GeneratorHelper.OpenModel(newFile) as nHydrate.Generator.nHydrateGeneratorProject;
                    }
                    catch (Exception ex)
                    {
                        System.Windows.Forms.MessageBox.Show("An error occurred while importing the legacy modelRoot.", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                        return;
                    }
                    finally
                    {
                        if (File.Exists(newFile))
                            File.Delete(newFile);
                    }

                    try
                    {
                        var oldModel = project.Model as nHydrate.Generator.Models.ModelRoot;

                        model.TransformNames = oldModel.TransformNames;
                        model.CompanyName = oldModel.CompanyName;
                        model.ProjectName = oldModel.ProjectName;
                        model.Copyright = oldModel.Copyright;
                        model.CreatedByColumnName = oldModel.Database.CreatedByColumnName;
                        model.CreatedDateColumnName = oldModel.Database.CreatedDateColumnName;
                        model.DefaultNamespace = oldModel.DefaultNamespace;
                        model.ModifiedByColumnName = oldModel.Database.ModifiedByColumnName;
                        model.ModifiedDateColumnName = oldModel.Database.ModifiedDateColumnName;
                        model.SQLServerType = (DatabaseTypeConstants)Enum.Parse(typeof(DatabaseTypeConstants), oldModel.SQLServerType.ToString());
                        model.StoredProcedurePrefix = oldModel.StoredProcedurePrefix;
                        model.TenantPrefix = oldModel.TenantPrefix;
                        model.AllowMocks = oldModel.AllowMocks;
                        model.TimestampColumnName = oldModel.Database.TimestampColumnName;
                        model.UseUTCTime = oldModel.UseUTCTime;
                        model.Version = oldModel.Version;

                        #region Load Tables
                        foreach (var table in oldModel.Database.Tables.ToList())
                        {
                            var newEntity = new Entity(model.Partition);
                            model.Entities.Add(newEntity);
                            addedElements.Add(newEntity);
                            newEntity.AllowAuditTracking = table.AllowAuditTracking;
                            newEntity.AllowCreateAudit = table.AllowCreateAudit;
                            newEntity.AllowModifyAudit = table.AllowModifiedAudit;
                            newEntity.AllowTimestamp = table.AllowTimestamp;
                            newEntity.CodeFacade = table.CodeFacade;
                            newEntity.Summary = table.Description;
                            newEntity.Immutable = table.Immutable;
                            newEntity.IsAssociative = table.AssociativeTable;
                            newEntity.IsGenerated = table.Generated;
                            newEntity.TypedEntity = (TypedEntityConstants)Enum.Parse(typeof(TypedEntityConstants), table.TypedTable.ToString(), true);
                            newEntity.Name = table.Name;
                            newEntity.Schema = table.DBSchema;
                            //DO NOT IMPORT METADATA

                            #region Load the columns
                            var maxSortOrder = 1;
                            foreach (var column in table.GetColumns())
                            {
                                var newField = new Field(model.Partition);
                                newEntity.Fields.Add(newField);
                                newField.CodeFacade = column.CodeFacade;
                                newField.Collate = column.Collate;
                                newField.DataType = (DataTypeConstants)Enum.Parse(typeof(DataTypeConstants), column.DataType.ToString());
                                newField.Default = column.Default;
                                newField.Summary = column.Description;
                                newField.Formula = column.Formula;
                                newField.FriendlyName = column.FriendlyName;
                                newField.Identity = (IdentityTypeConstants)Enum.Parse(typeof(IdentityTypeConstants), column.Identity.ToString());
                                newField.IsCalculated = column.ComputedColumn;
                                newField.IsGenerated = column.Generated;
                                newField.IsPrimaryKey = column.PrimaryKey;
                                newField.SortOrder = maxSortOrder++;

                                //Do not reset as it creates 2 indexes with PK
                                if (!newField.IsPrimaryKey)
                                    newField.IsIndexed = column.IsIndexed;

                                newField.IsReadOnly = column.IsReadOnly;
                                newField.IsUnique = column.IsUnique;
                                newField.Length = column.Length;
                                newField.Max = column.Max;
                                newField.Min = column.Min;
                                newField.Name = column.Name;
                                newField.Nullable = column.AllowNull;
                                newField.Scale = column.Scale;
                                newField.IsBrowsable = column.IsBrowsable;
                                newField.ValidationExpression = column.ValidationExpression;
                            }
                            #endregion

                            #region Composites
                            foreach (var component in table.ComponentList.ToList())
                            {
                                var newComposite = new Composite(model.Partition);
                                newEntity.Composites.Add(newComposite);
                                addedElements.Add(newComposite);
                                newComposite.CodeFacade = component.CodeFacade;
                                newComposite.Summary = component.Description;
                                newComposite.Name = component.Name;
                                newComposite.IsGenerated = component.Generated;

                                //Add the fields by looking them up in the new table
                                foreach (var column in component.GetColumns())
                                {
                                    var checkColumn = table.GetColumns().FirstOrDefault(x => x.Key == column.Key);
                                    if (checkColumn != null)
                                    {
                                        var tableField = newEntity.Fields.FirstOrDefault(x => x.Name == checkColumn.Name);
                                        if (tableField != null)
                                        {
                                            var newField = new CompositeField(model.Partition);
                                            newComposite.Fields.Add(newField);
                                            newField.FieldId = tableField.Id;
                                        }
                                    }
                                }

                            }
                            #endregion

                            #region Load Static Data
                            var index = 1;
                            foreach (nHydrate.Generator.Models.RowEntry data in table.StaticData)
                            {
                                var isProcessed = false;
                                foreach (nHydrate.Generator.Models.CellEntry cellEntry in data.CellEntries)
                                {
                                    var column = cellEntry.ColumnRef.Object as nHydrate.Generator.Models.Column;
                                    if (column != null)
                                    {
                                        var newColumn = newEntity.Fields.FirstOrDefault(x => x.Name == column.Name);
                                        if (newColumn != null)
                                        {
                                            var newData = new StaticData(model.Partition);
                                            newEntity.StaticDatum.Add(newData);
                                            newData.ColumnKey = newColumn.Id;
                                            newData.Value = cellEntry.Value;
                                            newData.OrderKey = index;
                                            isProcessed = true;
                                        }
                                    }
                                }
                                if (isProcessed)
                                    index++;
                            }
                            #endregion

                        }

                        foreach (var table in oldModel.Database.Tables.ToList())
                        {
                            if (table.ParentTable != null)
                            {
                                var child = model.Entities.FirstOrDefault(x => x.Name == table.Name);
                                var parent = model.Entities.FirstOrDefault(x => x.Name == table.ParentTable.Name);
                                child.ParentInheritedEntity = parent;
                            }
                        }

                        #endregion

                        #region Load Relations
                        foreach (nHydrate.Generator.Models.Table table in oldModel.Database.Tables)
                        {
                            foreach (nHydrate.Generator.Models.Relation relation in table.GetRelations())
                            {
                                var entity1 = model.Entities.First(x => x.Name == relation.ParentTable.Name);
                                var entity2 = model.Entities.First(x => x.Name == relation.ChildTable.Name);
                                if (entity2.ParentInheritedEntity != entity1)
                                {
                                    entity1.ChildEntities.Add(entity2);
                                    var newRelation = entity1.RelationshipList.First(x =>
                                        x.SourceEntity == entity1 &&
                                        x.TargetEntity == entity2 &&
                                        !x.FieldMapList().Any());
                                    newRelation.RoleName = relation.RoleName;

                                    foreach (nHydrate.Generator.Models.ColumnRelationship relationColumn in relation.ColumnRelationships)
                                    {
                                        var column1 = entity1.Fields.First(x => x.Name == relationColumn.ParentColumn.Name);
                                        var column2 = entity2.Fields.First(x => x.Name == relationColumn.ChildColumn.Name);
                                        var newRelationField = new RelationField(model.Partition);
                                        model.RelationFields.Add(newRelationField);
                                        newRelationField.SourceFieldId = column1.Id;
                                        newRelationField.TargetFieldId = column2.Id;
                                        newRelationField.RelationID = newRelation.Id;
                                    }
                                }
                            }
                        }
                        #endregion

                        #region Load Views
                        foreach (nHydrate.Generator.Models.CustomView item in oldModel.Database.CustomViews)
                        {
                            var newitem = new nHydrate.Dsl.View(model.Partition);
                            model.Views.Add(newitem);
                            addedElements.Add(newitem);
                            newitem.CodeFacade = item.CodeFacade;
                            newitem.Summary = item.Description;
                            newitem.IsGenerated = item.Generated;
                            newitem.Name = item.Name;
                            newitem.Schema = item.DBSchema;
                            newitem.SQL = item.SQL;

                            foreach (var column in item.GetColumns())
                            {
                                var newColumn = new ViewField(model.Partition);
                                newitem.Fields.Add(newColumn);
                                newColumn.DataType = (DataTypeConstants)Enum.Parse(typeof(DataTypeConstants), column.DataType.ToString());
                                newColumn.Default = column.Default;
                                newColumn.Summary = column.Description;
                                newColumn.FriendlyName = column.FriendlyName;
                                newColumn.Length = column.Length;
                                newColumn.IsGenerated = column.Generated;
                                //newColumn.Max = column.ma;
                                //newColumn.Min = column.;
                                newColumn.Name = column.Name;
                                newColumn.Nullable = column.AllowNull;
                                newColumn.Scale = column.Scale;
                            }
                        }
                        #endregion

                        #region Load Stored Procedures
                        foreach (nHydrate.Generator.Models.CustomStoredProcedure item in oldModel.Database.CustomStoredProcedures)
                        {
                            var newitem = new StoredProcedure(model.Partition);
                            model.StoredProcedures.Add(newitem);
                            addedElements.Add(newitem);
                            newitem.CodeFacade = item.CodeFacade;
                            newitem.Summary = item.Description;
                            newitem.IsGenerated = item.Generated;
                            newitem.IsExisting = item.IsExisting;
                            newitem.Name = item.Name;
                            newitem.Schema = item.DBSchema;
                            newitem.SQL = item.SQL;
                            newitem.DatabaseObjectName = item.DatabaseObjectName;

                            foreach (var parameter in item.GetParameters())
                            {
                                var newParameter = new StoredProcedureParameter(model.Partition);
                                newitem.Parameters.Add(newParameter);
                                newParameter.Nullable = parameter.AllowNull;
                                newParameter.DataType = (nHydrate.Dsl.DataTypeConstants)Enum.Parse(typeof(nHydrate.Dsl.DataTypeConstants), parameter.DataType.ToString());
                                newParameter.Default = parameter.Default;
                                newParameter.Summary = parameter.Description;
                                newParameter.IsGenerated = parameter.Generated;
                                newParameter.IsOutputParameter = parameter.IsOutputParameter;
                                newParameter.Length = parameter.Length;
                                newParameter.Scale = parameter.Scale;
                                newParameter.Name = parameter.Name;
                            }

                            foreach (var column in item.GetColumns())
                            {
                                var newColumn = new StoredProcedureField(model.Partition);
                                newitem.Fields.Add(newColumn);
                                newColumn.DataType = (DataTypeConstants)Enum.Parse(typeof(DataTypeConstants), column.DataType.ToString());
                                newColumn.Default = column.Default;
                                newColumn.Summary = column.Description;
                                newColumn.FriendlyName = column.FriendlyName;
                                newColumn.Length = column.Length;
                                //newColumn.Max = column.ma;
                                //newColumn.Min = column.;
                                newColumn.Name = column.Name;
                                newColumn.Nullable = column.AllowNull;
                                newColumn.Scale = column.Scale;
                            }

                        }
                        #endregion

                        nHydrateSerializationHelper.LoadInitialIndexes(model);

                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }

                }

                using (var transaction = store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
                {
                    diagram.AutoLayoutShapeElements(
                        diagram.NestedChildShapes.Where(x => addedElements.Contains(x.ModelElement)).ToList(),
                        Microsoft.VisualStudio.Modeling.Diagrams.GraphObject.VGRoutingStyle.VGRouteTreeNS,
                        Microsoft.VisualStudio.Modeling.Diagrams.GraphObject.PlacementValueStyle.VGPlaceNS,
                        true);
                    transaction.Commit();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                diagram.IsLoading = false;
                model.IsLoading = false;
            }

        }