Exemplo n.º 1
0
 public SQLScriptList RebuildConstraint(Boolean Check)
 {
     SQLScriptList list = new SQLScriptList();
     if (DefaultConstraint != null)
     {
         if ((!Check) || (DefaultConstraint.CanCreate)) list.Add(DefaultConstraint.Create());
         list.Add(DefaultConstraint.Drop());
     }
     return list;
 }
Exemplo n.º 2
0
        /// <summary>
        /// Создает таблицы в БД для сохранения/загрузки объектов переданного типа
        /// </summary>
        /// <returns></returns>
        public void CreateTableFor(Type type)
        {
            //Определение атрибута сохраняемой таблицы
            TableAttribute dbTable = (TableAttribute)type.GetCustomAttributes(typeof(TableAttribute), true).FirstOrDefault();

            if (!Database.Tables.Contains(dbTable.TableName, dbTable.TableScheme))
            {
                if (!Database.Schemas.Contains(dbTable.TableScheme))
                {
                    //Если схемы нет в БД, то производится ее создание
                    Schema newSchema = new Schema(Database, dbTable.TableScheme);
                    newSchema.Owner = "dbo";

                    //Create the schema on the instance of SQL Server.
                    newSchema.Create();

                    //Define an ObjectPermissionSet that contains the Update and Select object permissions.
                    ObjectPermissionSet obperset = new ObjectPermissionSet();
                    obperset.Add(ObjectPermission.Select);
                    obperset.Add(ObjectPermission.Update);
                    obperset.Add(ObjectPermission.Insert);
                    obperset.Add(ObjectPermission.Delete);

                    //Grant the set of permissions on the schema to the guest account.
                    newSchema.Grant(obperset, "sa");
                }

                Table newTable = new Table(Database, dbTable.TableName, dbTable.TableScheme);
                //определение своиств типа
                List <PropertyInfo> preProrerty = new List <PropertyInfo>(type.GetProperties());
                //определение своиств, имеющих атрибут "сохраняемое"
                List <PropertyInfo> properties =
                    preProrerty.Where(p => p.GetCustomAttributes(typeof(TableColumnAttribute), false).Length != 0).ToList();

                foreach (PropertyInfo t in properties)
                {
                    TableColumnAttribute tca =
                        (TableColumnAttribute)t.GetCustomAttributes(typeof(TableColumnAttribute), false).FirstOrDefault();

                    Column newColumn = new Column(newTable, tca.ColumnName);

                    DataType storedType = GetDataType(t, tca);
                    if (storedType != null)
                    {
                        newColumn.DataType = storedType;
                    }
                    else
                    {
                        throw new Exception("для типа " + t.PropertyType.Name + " не удается определить хранимый тип в БД");
                    }

                    newColumn.Nullable = true;

                    if (tca.ColumnName == dbTable.PrimaryKey)
                    {
                        // Определение своиств ключа
                        newColumn.Nullable          = false;
                        newColumn.Identity          = true;
                        newColumn.IdentitySeed      = 1;
                        newColumn.IdentityIncrement = 1;
                    }
                    newTable.Columns.Add(newColumn);
                }
                // Create a PK Index for the table
                Index index = new Index(newTable, "PK_" + dbTable.TableName)
                {
                    IndexKeyType = IndexKeyType.DriPrimaryKey
                };
                // The PK index will consist of 1 column, "ID"
                index.IndexedColumns.Add(new IndexedColumn(index, dbTable.PrimaryKey));
                // Add the new index to the table.
                newTable.Indexes.Add(index);
                // Physically create the table in the database
                newTable.Create();

                //Database.Tables.Add(newTable);

                if (newTable.Columns.Contains("IsDeleted"))
                {
                    // Определение своиств ключа
                    Column col = newTable.Columns["IsDeleted"];

                    string defName = dbTable.TableName + "_" + col.Name;

                    DefaultConstraint dc = col.AddDefaultConstraint(defName);
                    dc.Text = "((0))";
                    dc.Create();


                    col.Nullable = false;
                    col.Alter();

                    //Default def = new Default(Database, defName, dbTable.TableScheme)
                    //{
                    //    TextHeader = "CREATE DEFAULT " + dbTable.TableScheme + ".[" + defName + "] AS",
                    //    TextBody = "((0))"
                    //};
                    ////Create the default on the instance of SQL Server.
                    //def.Create();

                    ////Bind the default to a column in a table in AdventureWorks2012
                    //def.BindToColumn(dbTable.TableName, col.Name, dbTable.TableScheme);
                }
            }
            else
            {
                //Получение таблицы
                Table table = Database.Tables[dbTable.TableName, dbTable.TableScheme];
                //определение своиств типа
                List <PropertyInfo> preProrerty = new List <PropertyInfo>(type.GetProperties());
                //определение своиств, имеющих атрибут "сохраняемое"
                List <PropertyInfo> properties =
                    preProrerty.Where(p => p.GetCustomAttributes(typeof(TableColumnAttribute), false).Length != 0).ToList();

                //Проверка таблицы на наличие соответствующх колонок, их имен и типа хранимого значения
                foreach (PropertyInfo p in properties)
                {
                    TableColumnAttribute tca =
                        (TableColumnAttribute)p.GetCustomAttributes(typeof(TableColumnAttribute), false).FirstOrDefault();
                    //Для начала определяется, можно ли сохранить тип в БД
                    DataType storedType = GetDataType(p, tca);
                    if (storedType == null)
                    {
                        throw new Exception("для типа " + p.PropertyType.Name + " не удается определить хранимый тип в БД");
                    }

                    //Проверка наличия колонки с заданным именем в таблице
                    if (!table.Columns.Contains(tca.ColumnName))
                    {
                        //Если колонки с заданным именем нет в таблице
                        //то производится ее создание

                        Column newColumn = new Column(table, tca.ColumnName);
                        newColumn.DataType = storedType;
                        newColumn.Nullable = true;

                        if (tca.ColumnName == dbTable.PrimaryKey)
                        {
                            // Определение своиств ключа
                            newColumn.Nullable          = false;
                            newColumn.Identity          = true;
                            newColumn.IdentitySeed      = 1;
                            newColumn.IdentityIncrement = 1;

                            newColumn.Create();
                            //table.Columns.Add(newColumn);
                            // Create a PK Index for the table
                            Index index = new Index(table, "PK_" + dbTable.TableName)
                            {
                                IndexKeyType = IndexKeyType.DriPrimaryKey
                            };
                            // The PK index will consist of 1 column, "ID"
                            index.IndexedColumns.Add(new IndexedColumn(index, dbTable.PrimaryKey));
                            // Add the new index to the table.
                            table.Indexes.Add(index);

                            continue;
                        }
                        newColumn.Create();

                        continue;
                    }

                    //Проверка типа хранимого значения колонки
                    Column col = table.Columns[tca.ColumnName];
                    if (col.DataType.Name != storedType.Name)
                    {
                        //Если тип колонки в таблице не соответствует типу для хранения
                        //то производится смена типа
                        col.DataType = storedType;
                        col.Alter();

                        continue;
                    }
                    if (col.DataType.MaximumLength != storedType.MaximumLength && storedType.MaximumLength != 0)
                    {
                        //Если размер типа данных колонки в таблице не соответствует размеру для хранения
                        //то производится изменение размера
                        col.DataType.MaximumLength = storedType.MaximumLength;
                        col.Alter();

                        continue;
                    }
                }
            }
        }