Esempio n. 1
0
        public void MigrateStructure(IServiceLocator locator, IMigrationScriptBuilder script)
        {
            var collector = locator.Get <IEntityCollector>();

            if (collector == null)
            {
                throw new InvalidOperationException($"Provided locator doesn't have {typeof(IEntityCollector)}");
            }

            var entities = collector.GetEntityTypes().ToList();

            foreach (var entity in entities)
            {
                var table = m_dataModel.GetTableName(entity);

                var pk = m_convention.GetPrimaryKeyProperty(entity);

                script.CreateTable(
                    table,
                    m_dataModel.GetColumnName(pk),
                    pk.PropertyType,
                    PkHandlingHelper.IsPkAutogenerated(pk));

                var relations = m_dataModel.GetReferences(entity).ToList();

                var columns = m_dataModel.GetTableDataColumns(entity);
                foreach (var column in columns)
                {
                    try
                    {
                        if (column == pk)
                        {
                            continue;
                        }

                        var type       = SqlTypeMapper.GetColumnType(column);
                        var columnName = m_convention.GetColumnName(column);
                        script.CreateColumn(table, columnName, type.ColumnDeclarationTypeText, type.IsNullable, false);

                        var references =
                            relations.Where(r => (r.LeftEntityType == entity) && (r.LeftKeyColumnName == columnName));

                        foreach (var relation in references)
                        {
                            script.CreateForeignKey(
                                table,
                                columnName,
                                m_dataModel.GetTableName(relation.RightEntityType),
                                relation.RightKeyColumnName);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidOperationException($"Schema migration failed, table={table}, column={column}", ex);
                    }
                }
            }
        }
 public IEnumerable <PropertyInfo> GetTableDataColumns(Type entityType)
 {
     return(m_dataColumns.GetOrAdd(entityType, t => m_source.GetTableDataColumns(t).ToList()));
 }