コード例 #1
0
ファイル: CsvReaderTests.cs プロジェクト: sandrock/SrkCsv
 public void Csv1_Transformed_Semicolon()
 {
     var table = new Table<Csv1Row>();
     table.AddColumn(0, "Firstname", x => x.Target.FirstName = x.Value);
     table.AddColumn(1, "Lastname", x => x.Target.LastName = x.Value);
     table.AddColumn(2, "City", x => x.Target.City = x.Value);
     table.AddColumn(3, "Age", x =>
     {
         int age;
         var ok = int.TryParse(x.Value, out age);
         x.Target.Age = age;
         return ok;
     });
     var target = new CsvReader<Csv1Row>(table);
     target.CellSeparator = ';';
     target.HasHeaderLine = true;
     var reader = new StringReader(CsvFiles.Csv1.Replace(CsvFiles.Csv1Separator, ";"));
     var result = target.ReadToEnd(reader);
     Assert.IsNotNull(result);
     Assert.IsNotNull(result.Columns);
     Assert.IsNotNull(result.Rows);
     Assert.AreEqual(4, result.Rows.Count);
     Assert.AreEqual("Firstname", result.Rows[0].Cells[0].Value);
     ////Assert.AreEqual("Firstname", result.Rows[0].Target.FirstName);
     Assert.IsTrue(result.Rows[0].IsHeader);
     Assert.AreEqual("Gregory", result.Rows[1].Cells[0].Value);
     Assert.AreEqual("Gregory", result.Rows[1].Target.FirstName);
     Assert.AreEqual("Gorgini", result.Rows[2].Cells[1].Value);
     Assert.AreEqual("Gorgini", result.Rows[2].Target.LastName);
     Assert.AreEqual("Valenciennes", result.Rows[3].Cells[2].Value);
     Assert.AreEqual("Valenciennes", result.Rows[3].Target.City);
     Assert.AreEqual("100", result.Rows[3].Cells[3].Value);
     Assert.AreEqual(100, result.Rows[3].Target.Age);
 }
        protected void SetupBase(string resourcePath)
        {
            loader = new EntityLoader(MockRepository.GenerateStub<IFileController>());

            database = new Database("DB1");
            table1 = new Table("Table1");
            table1.AddColumn(new Column("ID") { Datatype = "int" });
            table1.AddColumn(new Column("BasicClass2_Index") { Datatype = "int" });
            database.AddEntity(table1);

            table2 = new Table("Table2");
            table2.AddColumn(new Column("ID") { Datatype = "int" });
            table2.AddColumn(new Column("BASIC_CLASS_1_ID"));
            database.AddEntity(table2);

            tableManyToMany = new Table("Class1Class2");
            tableManyToMany.AddColumn(new Column("Class1ID") { Datatype = "int" });
            tableManyToMany.AddColumn(new Column("Class2ID") { Datatype = "int" });
            database.AddTable(tableManyToMany);

            relationship = table1.CreateRelationshipTo(table2);
            relationship.PrimaryKey.AddColumn("ID");
            relationship.ForeignKey.AddColumn("BASIC_CLASS_1_ID");

            // Call we are testing
            mappingSet = loader.GetEntities(new[] { Path.Combine("Resources", resourcePath) }, database);
        }
コード例 #3
0
        public void WhenCreateTableWithNamedPrimaryKey_GetCorrespondingTableScript()
        {
            var table = new Table("TestTables");
            table.AddColumn("Key1", new Int()).PrimaryKey("PrimaryKeyForTestTables");
            table.AddColumn("Key2", new Int()).PrimaryKey("PrimaryKeyForTestTables");

            var createScript = table.GetUpScript().Single();

            Assert.Equal("CREATE TABLE TestTables\r\n(\r\nKey1 int NOT NULL,\r\nKey2 int NOT NULL,\r\nCONSTRAINT PrimaryKeyForTestTables PRIMARY KEY (Key1,Key2)\r\n)", createScript);
        }
コード例 #4
0
        public void WhenCreateTableWithAutoIncrementAsNoPrimaryKey_GetCorrespondingTableScript()
        {
            var table = new Table("TestTables");
            table.AddColumn("MyIdColumn", new Int()).AutoIncrement(primaryKey: false);
            table.AddColumn("MyValue", new NVarChar(100));

            var createScript = table.GetUpScript().Single();

            Assert.Equal("CREATE TABLE TestTables\r\n(\r\nMyIdColumn int IDENTITY(1,1),\r\nMyValue nvarchar(100)\r\n)", createScript);
        }
コード例 #5
0
        public void WhenCreateTableWithNotNullAndPrimaryKey_GetCorrespondingTableScript()
        {
            var table = new Table("TestTables");
            table.AddColumn("MyIdColumn", new Int()).PrimaryKey();
            table.AddColumn("MyValue", new NVarChar(100));

            var createScript = table.GetUpScript().Single();

            Assert.Equal("CREATE TABLE TestTables\r\n(\r\nMyIdColumn int NOT NULL PRIMARY KEY,\r\nMyValue nvarchar(100)\r\n)", createScript);
        }
コード例 #6
0
        public void WhenCreateTableWithNamedUniquesAndOneUniqueColumn_GetCorrespondingTableScript()
        {
            var table = new Table("TestTables");
            table.AddColumn("Col1", new Int()).Unique("PrimaryKeyForTestTables");
            table.AddColumn("Col2", new Int()).Unique("PrimaryKeyForTestTables");
            table.AddColumn("Col3", new Int()).Unique();

            var createScript = table.GetUpScript().Single();

            Assert.Equal("CREATE TABLE TestTables\r\n(\r\nCol1 int,\r\nCol2 int,\r\nCol3 int UNIQUE,\r\nCONSTRAINT PrimaryKeyForTestTables UNIQUE (Col1,Col2)\r\n)", createScript);
        }
コード例 #7
0
        public override void AddDbChanges(List<IDbChange> tableCollection)
        {
            var table = new Table(_tableName);
            table.AddColumn("Id", new Int()).PrimaryKey().AutoIncrement();
            table.AddColumn("InstallationName", new NVarChar(1024)).Unique().NotNull();
            table.AddColumn("PreviousVersion", new Int()).NotNull();
            table.AddColumn("StartedInstallingVersion", new Int()).NotNull();
            table.AddColumn("InstalledVersion", new Int()).NotNull();

            tableCollection.Add(table);
        }
コード例 #8
0
        public static Database TestDatabase()
        {
            Database db = new Database("Test Database");

            var t1 = new Table("Table1");
            db.AddTable(t1);
            t1.AddColumn(new Column("Column1") { InPrimaryKey = true, Datatype = "int", OrdinalPosition = 0, Size = 4});
            t1.AddColumn(new Column("Column2") { Datatype = "nvarchar", OrdinalPosition = 1, Size = 100 });
            t1.AddColumn(new Column("Column3") { Datatype = "datetime", OrdinalPosition = 2, Size = 8 });

            t1.AddIndex(new Index("PK_Table1") { IsUnique = true, Datatype = DatabaseIndexType.PrimaryKey}).AddColumn("Column1");
            t1.AddKey(new Key("PK_Table1", DatabaseKeyType.Primary)).AddColumn("Column1").AddColumn("Column2");

            return db;
        }
コード例 #9
0
        public void The_Rule_Fails_But_Only_For_The_Parent()
        {
            var set = new MappingSetImpl();
            var parentEntity = new EntityImpl("Parent");
            var childEntity = new EntityImpl("Child");
            childEntity.Parent = parentEntity;
            var property = new PropertyImpl("Property1");
            parentEntity.AddProperty(property);
            set.EntitySet.AddEntity(parentEntity);
            set.EntitySet.AddEntity(childEntity);

            var table = new Table("Table1");
            var column = new Column("Column1");
            table.AddColumn(column);
            set.Database.AddTable(table);

            var rule = new CheckAllPropertiesMappedRule();
            var result = rule.Run(set);

            Assert.That(result.HasIssues);
            Assert.That(result.Issues, Has.Count(1));

            var issue = result.Issues[0];
            Assert.That(issue.ErrorLevel, Is.EqualTo(ValidationErrorLevel.Warning));
            Assert.That(issue.Object, Is.SameAs(property));
            StringAssert.Contains("Property1", issue.Description);
            StringAssert.Contains("Parent", issue.Description);
        }
コード例 #10
0
        public void Form_Is_Set_Up()
        {
            IComponentSpecificationForm form = MockRepository.GenerateMock<IComponentSpecificationForm>();
            IMainPanel panel = MockRepository.GenerateMock<IMainPanel>();

            var mappingSet = new MappingSetImpl();
            var entity = new EntityImpl("Entity1");
            entity.AddProperty(new PropertyImpl("Property1"));
            var table = new Table("Table1");
            table.AddColumn(new Column("Column1"));
            table.AddColumn(new Column("Street"));
            mappingSet.EntitySet.AddEntity(entity);

            mappingSet.ChangeMappedColumnFor(entity.Properties.First()).To(table.Columns[0]);

            ComponentSpecification spec = new ComponentSpecificationImpl("Address");
            spec.AddProperty(new ComponentPropertyImpl("Street"));
            Component component = spec.CreateImplementedComponentFor(entity, "Street");
            mappingSet.EntitySet.AddComponentSpecification(spec);

            var mapping = new ComponentMappingImpl {ToComponent = component, FromTable = table};
            mapping.AddPropertyAndColumn(component.Properties[0], table.Columns[0]);
            mappingSet.AddMapping(mapping);

            form.Expect(f => f.SetProperties(null))
                .IgnoreArguments()
                .WhenCalled(action => Assert.That(((IEnumerable<ComponentProperty>)action.Arguments[0]).Count(), Is.EqualTo(1)));

            form.Expect(f => f.SetUsages(null))
                .IgnoreArguments()
                .WhenCalled(action => Assert.That(((IEnumerable<Entity>)action.Arguments[0]).Count(), Is.EqualTo(1)));

            form.Expect(f => f.SetFullEntityList(null))
                .IgnoreArguments()
                .WhenCalled(action => Assert.That(((IEnumerable<Entity>)action.Arguments[0]).Count(), Is.EqualTo(1)));

            ComponentSpecificationPresenter presenter = new ComponentSpecificationPresenter(panel, form);
            presenter.AttachToModel(spec);

            form.AssertWasCalled(f => f.Clear());
            form.AssertWasCalled(f => f.SpecName = spec.Name);
            form.AssertWasCalled(f => f.SetVirtualProperties(spec.Ex));

            form.VerifyAllExpectations();
        }
コード例 #11
0
        public void WhenColumnWithNotNull_GetCorrespondingTableScript()
        {
            var table = new Table("TestTables");
            table.AddColumn("MyColumn", new Int()).NotNull();

            var createScript = table.GetUpScript().Single();

            Assert.Equal("CREATE TABLE TestTables\r\n(\r\nMyColumn int NOT NULL\r\n)", createScript);
        }
コード例 #12
0
ファイル: ModelSetup.cs プロジェクト: uQr/Visual-NHibernate
        private static ITable CreateTable(IDatabase db, string tableName)
        {
            var table = new Table(tableName);
            table.AddColumn(new Column("Column1"));
            table.AddColumn(new Column("Column2"));
            table.AddColumn(new Column("Column3"));

            var primaryKey = new Key("PrimaryKey", DatabaseKeyType.Primary);
            table.AddKey(primaryKey);
            var foreignKey = new Key("ForeignKey", DatabaseKeyType.Foreign);
            table.AddKey(foreignKey);

            primaryKey.AddColumn("Column1");
            foreignKey.AddColumn("Column1");

            db.AddTable(table);

            return table;
        }
コード例 #13
0
        public void The_Rule_Fails()
        {
            var set = new MappingSetImpl();
            var entity = new Table("Table1");
            set.Database.AddTable(entity);
            entity.AddColumn(new Column("Column1"));
            var duplicate = new Column("Column1");
            entity.AddColumn(duplicate);

            DatabaseNamingRule rule = new DatabaseNamingRule();
            var result = rule.Run(set);

            Assert.That(result.Issues, Has.Count(1));

            var issue = result.Issues[0];
            Assert.That(issue.ErrorLevel, Is.EqualTo(ValidationErrorLevel.Error));
            Assert.That(issue.Object, Is.SameAs(duplicate));
            StringAssert.Contains("Column1", issue.Description);
        }
コード例 #14
0
        public void Should_Return_This()
        {
            const string expectedXML = @"<Table>" + When_Serialising_An_Empty_Table.ScriptBaseXml +
                                       @"<Columns>" + When_Serialising_An_Empty_Column.BasicColumnXml + @"</Columns>" +
                                       @"</Table>";
            Table table = new Table("Entity1");
            table.AddColumn(new Column("Entity1"));

            string outputXML = table.Serialise(new DatabaseSerialisationScheme());
            outputXML = XmlSqueezer.RemoveWhitespaceBetweenElements(outputXML);
            Assert.That(outputXML, Is.EqualTo(expectedXML));
        }
        public void It_Should_Serialise_To_This()
        {
            Table table = new Table("Table1");
            Column column = new Column("Column1");
            table.AddColumn(column);

            var dis = new DiscriminatorBuilder()
                .SingleConditionDiscriminator(column, Operator.Equal, new ExpressionValueImpl("5"));

            string outputXML = new EntitySetSerialisationScheme().SerialiseDiscriminator(dis);
            outputXML = XmlSqueezer.RemoveWhitespaceBetweenElements(outputXML);
            Assert.That(outputXML, Is.EqualTo(FullDiscriminatorXml));
        }
コード例 #16
0
ファイル: Program.cs プロジェクト: Badgerati/Table
        static void Main(string[] args)
        {
            Table table = new Table(2);
            table.AddRow(new object[] { "hello", 100 });

            TableRow tr = table[0];
            Console.WriteLine(tr["0"] + " -- " + tr["1"]);

            table.AddColumn("age");
            table[0]["age"] = 2;

            tr = table[0];
            Console.WriteLine(tr["0"] + " -- " + tr["1"] + " -- " + tr["age"]);
        }
コード例 #17
0
        public void Should_Return_This()
        {
            const string expectedXML = KeyWithReferencedKeyXml;

            Table table1 = new Table("Table1");
            table1.AddColumn(new Column("Column1"));
            Key key = new Key("Entity1");
            Table table2 = new Table("Table2");
            key.ReferencedKey = new Key("ForeignKey") { Parent = table2 };

            string outputXML = key.Serialise(new DatabaseSerialisationScheme());
            outputXML = XmlSqueezer.RemoveWhitespaceBetweenElements(outputXML);
            Assert.That(outputXML, Is.EqualTo(expectedXML));
        }
コード例 #18
0
        public void It_Should_Be_Reconstructed_Correctly()
        {
            const string xml = When_Serialising_Key_With_Columns.KeyWithColumnsXml;
            XmlDocument document = new XmlDocument();
            document.LoadXml(xml);

            Table table1 = new Table("Table1");
            table1.AddColumn(new Column("Column1"));

            IKey key = new DatabaseDeserialisationScheme().ProcessKeyNode(document.DocumentElement, table1, new Database(""));

            Assert.That(key.Columns, Has.Count(1));
            Assert.That(key.Columns[0], Is.SameAs(table1.Columns[0]));
        }
コード例 #19
0
        public void AddForeignKeyConstraintOneOneColumnWithGenericExtensionMethod_GetCorrectInformationInTable()
        {
            // Arrange
            var table = new Table<ClubMember>("ClubMembers");

            // Act
            table.AddAutoIncrementColumn(m => m.Id);
            table.AddColumn(m => m.ClubId).ForeignKey<Club>(m => m.ClubId);

            // Assert
            Assert.Equal(1, table.Columns.Where(m => m.ForeignKey != null).Count());
            Assert.Equal("ClubId", table.Columns.First(m => m.ForeignKey != null).ForeignKey.ColumnName);
            Assert.Equal("Clubs", table.Columns.First(m => m.ForeignKey != null).ForeignKey.TableName);
        }
コード例 #20
0
ファイル: CsvReaderTests.cs プロジェクト: sandrock/SrkCsv
 public void Csv1_Raw()
 {
     var table = new Table();
     table.AddColumn(0, "Firstname");
     table.AddColumn(1, "Lastname");
     table.AddColumn(2, "City");
     table.AddColumn(3, "Age");
     var target = new CsvReader(table);
     target.CellSeparator = ',';
     target.HasHeaderLine = true;
     var reader = new StringReader(CsvFiles.Csv1);
     var result = target.ReadToEnd(reader);
     Assert.IsNotNull(result);
     Assert.IsNotNull(result.Columns);
     Assert.IsNotNull(result.Rows);
     Assert.AreEqual(4, result.Rows.Count);
     Assert.AreEqual("Firstname", result.Rows[0].Cells[0].Value);
     Assert.IsTrue(result.Rows[0].IsHeader);
     Assert.AreEqual("Gregory", result.Rows[1].Cells[0].Value);
     Assert.AreEqual("Gorgini", result.Rows[2].Cells[1].Value);
     Assert.AreEqual("Valenciennes", result.Rows[3].Cells[2].Value);
     Assert.AreEqual("100", result.Rows[3].Cells[3].Value);
 }
コード例 #21
0
        public void ColumnsUpdatedAfterCall()
        {
            ICollectionForm<IColumn> form = MockRepository.GenerateMock<ICollectionForm<IColumn>>();
            IColumnContainer obj = new Table("Table1");
            IMainPanel panel = MockRepository.GenerateMock<IMainPanel>();

            //var presenter = (ItemCollectionPresenter<IColumn>) new ColumnCollectionPresenter(panel, form);
            //presenter.AttachToModel(obj);

            form.AssertWasCalled(f => f.Items = obj.Columns);

            obj.AddColumn(new Column("asdsad"));

            form.AssertWasCalled(f => f.Items = obj.Columns, c => c.Repeat.Twice());
        }
コード例 #22
0
        private void buttonRunHBM2ModelTransform_Click(object sender, RoutedEventArgs args)
        {
            var loader = new EntityLoader(new FileController());
            var database = new Database("DB1", ArchAngel.Providers.EntityModel.Controller.DatabaseLayer.DatabaseTypes.SQLServer2005);
            var table = new Table("TableName", "");
            table.AddColumn(new Column("ID"));
            table.AddColumn(new Column("Speed"));
            table.AddColumn(new Column("Name"));
            table.AddColumn(new Column("Speed"));
            table.AddColumn(new Column("Discriminator"));
            table.AddColumn(new Column("Car_Make"));
            table.AddColumn(new Column("Bike_Model"));

            database.AddTable(table);
            loader.GetEntities(new[] {"nhtest.xml"}, database);
        }
コード例 #23
0
        public void TestDeleteFrom()
        {
            DB          db       = new DB("MyDB", "admin", "admin");
            Table       newTable = new Table("newTable");
            TableColumn column   = new TableColumn("a");

            column.AddString("name");
            column.AddString("surname");
            string table = newTable.GetName();

            newTable.AddColumn(column);
            db.AddTable(newTable);
            List <string> col       = column.GetColumns();
            Condition     condition = new Condition(Condition.Operations.equals, "name", column.GetTableColumnName());

            db.DeleteFrom(table, col, condition);

            Assert.AreEqual("surname", col[0]);
        }
コード例 #24
0
        public string GetInitialQQPopulationsString()
        {
            BottomiumVector initialPopsBR
                = CalculateInitialQQPopulationsWithDimuonBranchingRatiosIncluded();
            Table <string> initialPopsBRStrings = Table <string> .CreateFromFormattedTableString(
                initialPopsBR.GetVectorString(
                    description: "N^i_AA,nl/N^f_pp,1S",
                    extractGammaTot3P: true));

            BottomiumVector initialPops        = CalculateInitialQQPopulations();
            Table <string>  initialPopsStrings = Table <string> .CreateFromFormattedTableString(
                initialPops.GetVectorString(
                    description: "N^i_AA,nl/N^f_pp,1S/B(nS→µ±)",
                    extractGammaTot3P: true));

            initialPopsBRStrings.AddColumn(initialPopsStrings.GetColumn(1), string.Empty);

            return(initialPopsBRStrings.ToFormattedTableString());
        }
コード例 #25
0
        public string Run(DataBase database)
        {
            if (database.CanDo("", ""))
            {
                database.AddTable(new Table(m_table));
                Table table = database.SearchTableByName(m_table);

                foreach (String column in m_newColumns)
                {
                    table.AddColumn(new Column(column));
                }

                return(Messages.CreateTableSuccess);
            }
            else
            {
                return(Messages.SecurityNotSufficientPrivileges);
            }
        }
コード例 #26
0
        public void AliasedTableShouldfailIfRequestedWithoutalias()
        {
            var   db    = new Database();
            Table table = db.AddTable("TBL");

            table.AddColumn(new Column("ID", typeof(int)));

            var row = table.NewRow(3);

            table.AddRow(row);

            string         query       = "Select ID from [TBL] as A where TBL.ID=3";
            SQLInterpreter interpreter = new SQLInterpreter(db);

            Assert.ThrowsException <InvalidOperationException>(() =>
            {
                var result = interpreter.Execute(query)[0];
            });
        }
コード例 #27
0
    /// <summary>
    /// Adds a column to the table.
    /// </summary>
    /// <param name="table">The table to add the column to.</param>
    /// <param name="column">The column to add.</param>
    /// <param name="configure">Delegate that can be used to configure the added column.</param>
    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public static Table AddColumn(this Table table, string column, Action <TableColumn>?configure = null)
    {
        if (table is null)
        {
            throw new ArgumentNullException(nameof(table));
        }

        if (column is null)
        {
            throw new ArgumentNullException(nameof(column));
        }

        var tableColumn = new TableColumn(column);

        configure?.Invoke(tableColumn);

        table.AddColumn(tableColumn);
        return(table);
    }
コード例 #28
0
    /// <summary>
    /// Adds multiple columns to the table.
    /// </summary>
    /// <param name="table">The table to add the column to.</param>
    /// <param name="columns">The columns to add.</param>
    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public static Table AddColumns(this Table table, params TableColumn[] columns)
    {
        if (table is null)
        {
            throw new ArgumentNullException(nameof(table));
        }

        if (columns is null)
        {
            throw new ArgumentNullException(nameof(columns));
        }

        foreach (var column in columns)
        {
            table.AddColumn(column);
        }

        return(table);
    }
コード例 #29
0
        public async Task detect_new_primary_key_change()
        {
            await CreateSchemaObjectInDatabase(theTable);

            var table = new Table("deltas.states");

            table.AddColumn <string>("abbreviation");

            await CreateSchemaObjectInDatabase(table);

            table.ModifyColumn("abbreviation").AsPrimaryKey();

            var delta = await table.FindDelta(theConnection);

            delta.PrimaryKeyDifference.ShouldBe(SchemaPatchDifference.Update);
            delta.HasChanges().ShouldBeTrue();

            await AssertNoDeltasAfterPatching(theTable);
        }
コード例 #30
0
        public void InitialStart() //первый запуск либо самая верхняя точка программы где выводятся доступные жесткие диски
        {
            var rule = new Rule("[red]Drive Catalogue:[/]:");

            rule.Alignment = Justify.Left;
            rule.RuleStyle("purple dim");
            var table = new Table();

            table.Expand();
            table.AddColumn("[darkcyan]Drives:[/]");

            DriveInfo[] di = DriveInfo.GetDrives();
            foreach (DriveInfo drive in di)
            {
                table.AddRow(new Markup($"[blue]{drive.Name}[/]"));
            }
            AnsiConsole.Render(rule);
            AnsiConsole.Render(table);
        }
コード例 #31
0
        public void GetRowCount_ReturnCoherentValue()
        {
            Table  table  = new Table("testRowCount");
            Column column = new Column("column1", DataTypesFactory.GetDataTypesFactory().GetDataType(TypesKeyConstants.StringTypeKey));

            table.AddColumn(column);
            int    rowCount = table.GetRowCount();
            Row    row;
            string genericData = "aaa";

            for (int i = 0; i < 200; i++)
            {
                row = table.CreateRowDefinition();
                Assert.IsTrue(column.dataType.IsAValidDataType(genericData));
                row.GetCell(column.columnName).data = genericData;
                table.AddRow(row);
                Assert.AreEqual(rowCount + i + 1, table.GetRowCount());
            }
        }
コード例 #32
0
        public void Select_GoodArguments_TableEmpty_ShouldntFindResults()
        {
            IDatabaseContainer databaseContainer = ObjectConstructor.CreateDatabaseContainer();
            Database           database          = new Database("aa");

            databaseContainer.AddDatabase(database); //Notice the references. (this database object references, no the 'referencias')
            ITable table  = new Table("table1");
            Column column = new Column("c1", DataTypesFactory.GetDataTypesFactory().GetDataType(TypesKeyConstants.StringTypeKey));

            table.AddColumn(column);
            database.AddTable(table);
            Select select = CreateSelect(databaseContainer, database.databaseName, table.tableName, true);

            select.whereClause.AddCritery(column.columnName, table.GetColumn(column.columnName).dataType.GetDataTypeDefaultValue(), Operator.equal);
            Assert.IsTrue(select.ValidateParameters());
            Assert.IsTrue(table.GetRowCount() == 0); //Maybe assert.equal
            select.Execute();
            Assert.IsTrue(select.GetAfectedRowCount() == 0);
        }
コード例 #33
0
//    [UnitTestFunction]
        public static void TestVerticalAlign()
        {
            Document doc = new Document();
            Section  sec = doc.Sections.AddSection();
            Table    tbl = sec.AddTable();

            tbl.AddColumn();
            tbl.Rows.Height = 40;
            tbl.Rows.AddRow().VerticalAlignment = VerticalAlignment.Bottom;
            tbl[0, 0].AddParagraph("Text");
            tbl.Borders.Visible = true;

            DocumentRenderer docRndrr = new DocumentRenderer();

            docRndrr.Render(doc, "RtfVerticalAlign.txt", null);
            File.Copy("RtfVerticalAlign.txt", "RtfVerticalAlign.rtf", true);
            System.Diagnostics.Process.Start("RtfVerticalAlign.txt");
            DdlWriter.WriteToFile(doc, "RtfVerticalAlign.mdddl");
        }
コード例 #34
0
        public void AddRecord()
        {
            var db   = new Database();
            var cars = new Table("cars");

            cars.AddColumn(new TextColumn("name"));
            db.AddTable(cars);

            var record = new Record
            {
                ["name"] = "BMW"
            };

            db["cars"].AddRecord(record);

            var result = db.GetValue <string>("SELECT name FROM cars ORDER BY id DESC");

            Assert.AreEqual("BMW", result);
        }
コード例 #35
0
        public void DeleteRow_TheRowIsReferedForAnotherRows_DontDeleteTheRowRefered()
        {
            //Construction phase
            IDatabaseContainer container = ObjectConstructor.CreateDatabaseContainer();
            Database           db        = new Database("database1");
            ITable             table1    = new Table("table1");
            Column             column1t1 = new Column("c1t1", DataTypesFactory.GetDataTypesFactory().GetDataType(TypesKeyConstants.IntTypeKey));

            table1.AddColumn(column1t1);
            table1.primaryKey.AddKey(column1t1);
            db.AddTable(table1);
            ITable table2    = new Table("table2");
            Column column1t2 = new Column("c1t2", DataTypesFactory.GetDataTypesFactory().GetDataType(TypesKeyConstants.IntTypeKey));

            table2.AddColumn(column1t2);
            table2.primaryKey.AddKey(column1t2);
            db.AddTable(table2);
            container.AddDatabase(db);
            table2.foreignKey.AddForeignKey(column1t2, column1t1);
            //Insert some data
            Row rowT1;
            int limit = 10;

            for (int i = 0; i <= limit; i++)
            {
                rowT1 = table1.CreateRowDefinition();
                rowT1.GetCell(column1t1.columnName).data = "" + i;
                table1.AddRow(rowT1);
            }
            Row rowT2 = table2.CreateRowDefinition();

            rowT2.GetCell(column1t2.columnName).data = "" + limit;
            table2.AddRow(rowT2);
            //Test
            int    numberOfRows = table1.GetRowCount();
            Delete delete       = CreateDelete(container, db.databaseName, table1.tableName);

            delete.whereClause.AddCritery(column1t1.columnName, "" + 11, Operator.less);
            Assert.IsTrue(delete.ValidateParameters());
            delete.Execute();
            Assert.AreEqual(table2.GetRowCount(), numberOfRows - delete.GetAfectedRowCount());
            Assert.IsTrue(table1.GetColumn(column1t1.columnName).ExistCells(rowT2.GetCell(column1t2.columnName).data));
        }
コード例 #36
0
ファイル: DeletionTests.cs プロジェクト: IM-SQL/IMSQL
        public void TopDeleteWithTiesShouldFail()
        {
            var   db    = new Database();
            Table table = db.AddTable("TBL");

            table.AddColumn(new Column("ID", typeof(int)));
            for (int i = 0; i < 200; i++)
            {
                var row = table.NewRow(i);
                table.AddRow(row);
            }
            string         query       = "Delete TOP(50) with ties from [TBL]";
            SQLInterpreter interpreter = new SQLInterpreter(db);

            Assert.ThrowsException <ParseException>(() =>
            {
                interpreter.Execute(query);
            });
        }
コード例 #37
0
ファイル: Columns.cs プロジェクト: gitfool/spectre.console
    /// <inheritdoc/>
    protected override IEnumerable <Segment> Render(RenderContext context, int maxWidth)
    {
        var maxPadding = Math.Max(Padding.GetLeftSafe(), Padding.GetRightSafe());

        var itemWidths  = _items.Select(item => item.Measure(context, maxWidth).Max).ToArray();
        var columnCount = CalculateColumnCount(maxWidth, itemWidths, _items.Count, maxPadding);

        if (columnCount == 0)
        {
            // Temporary work around for extremely small consoles
            columnCount = 1;
        }

        var table = new Table();

        table.NoBorder();
        table.HideHeaders();
        table.PadRightCell = false;

        if (Expand)
        {
            table.Expand();
        }

        // Add columns
        for (var index = 0; index < columnCount; index++)
        {
            table.AddColumn(new TableColumn(string.Empty)
            {
                Padding = Padding,
                NoWrap  = true,
            });
        }

        // Add rows
        for (var start = 0; start < _items.Count; start += columnCount)
        {
            table.AddRow(_items.Skip(start).Take(columnCount).ToArray());
        }

        return(((IRenderable)table).Render(context, maxWidth));
    }
コード例 #38
0
        public async Task read_fk()
        {
            await theConnection.OpenAsync();

            await theConnection.ResetSchema("tables");


            var states = new Table("states");

            states.AddColumn <int>("id").AsPrimaryKey();

            await CreateSchemaObjectInDatabase(states);


            var table = new Table("people");

            table.AddColumn <int>("id").AsPrimaryKey();
            table.AddColumn <string>("first_name").AddIndex();
            table.AddColumn <string>("last_name").AddIndex(i =>
            {
                i.IsConcurrent = true;
                i.Method       = IndexMethod.hash;
            });

            table.AddColumn <int>("state_id").ForeignKeyTo(states, "id", onDelete: CascadeAction.Cascade, onUpdate: CascadeAction.Restrict);

            await CreateSchemaObjectInDatabase(table);

            var existing = await table.FetchExisting(theConnection);


            var fk = existing.ForeignKeys.Single();

            fk.Name.ShouldBe("fkey_people_state_id");

            fk.ColumnNames.Single().ShouldBe("state_id");
            fk.LinkedNames.Single().ShouldBe("id");
            fk.LinkedTable.Name.ShouldBe("states");

            fk.OnDelete.ShouldBe(CascadeAction.Cascade);
            fk.OnUpdate.ShouldBe(CascadeAction.Restrict);
        }
コード例 #39
0
        public void Should_Return_This()
        {
            const string expectedXML = KeyWithReferencedKeyXml;

            Table table1 = new Table("Table1");

            table1.AddColumn(new Column("Column1"));
            Key   key    = new Key("Entity1");
            Table table2 = new Table("Table2");

            key.ReferencedKey = new Key("ForeignKey")
            {
                Parent = table2
            };

            string outputXML = key.Serialise(new DatabaseSerialisationScheme());

            outputXML = XmlSqueezer.RemoveWhitespaceBetweenElements(outputXML);
            Assert.That(outputXML, Is.EqualTo(expectedXML));
        }
コード例 #40
0
ファイル: ModificationTests.cs プロジェクト: IM-SQL/IMSQL
        public void AddAssignmentStringUpdateTest()
        {
            var   db    = new Database();
            Table table = db.AddTable("TBL");

            table.AddColumn(new Column("ID", typeof(string)));

            var row = table.NewRow("hola");

            table.AddRow(row);

            string         query       = "Update [TBL] set ID +='-chau'";
            SQLInterpreter interpreter = new SQLInterpreter(db);

            var result   = interpreter.Execute(query)[0];
            int affected = result.RowsAffected;

            Assert.AreEqual(1, affected, "There should be one row affected");
            Assert.AreEqual("hola-chau", table.GetRow(0)["ID"], "The updated value was not present on the Table");
        }
        public void Setup()
        {
            database  = new Database("Db1");
            entitySet = new EntitySetImpl();

            table = new Table("Table1");
            table.AddColumn(new Column("AddressStreet"));

            var entity1 = new EntityImpl("Entity1");

            componentSpec = new ComponentSpecificationImpl("Address");
            entitySet.AddComponentSpecification(componentSpec);
            componentSpec.AddProperty(new ComponentPropertyImpl("Street"));

            component1 = componentSpec.CreateImplementedComponentFor(entity1, "HomeAddress");
            component2 = componentSpec.CreateImplementedComponentFor(entity1, "WorkAddress");

            database.AddTable(table);
            entitySet.AddEntity(entity1);
        }
コード例 #42
0
        public void The_Rule_Passes()
        {
            var set = new MappingSetImpl();
            var entity = new EntityImpl("Entity1");
            var property = new PropertyImpl("Property1");
            entity.AddProperty(property);
            set.EntitySet.AddEntity(entity);

            var table = new Table("Table1");
            var column = new Column("Column1");
            table.AddColumn(column);
            set.Database.AddTable(table);

            set.ChangeMappedColumnFor(property).To(column);

            var rule = new CheckAllPropertiesMappedRule();
            var result = rule.Run(set);

            Assert.That(result.HasIssues, Is.False);
        }
コード例 #43
0
ファイル: InsertionTests.cs プロジェクト: IM-SQL/IMSQL
        public void InsertWithSubquery()
        {
            var   db    = new Database();
            Table table = db.AddTable("TBL");

            table.AddColumn(new Column("A", typeof(int)));
            var row = table.NewRow(1);

            table.AddRow(row);

            var interpreter = new SQLInterpreter(db);
            SQLExecutionResult result;

            for (int i = 1; i < 10; i++)
            {
                int currentRowCount = table.Rows.Count();
                result = interpreter.Execute("Insert into TBL(A) select A*2 from TBL ")[0];
                Assert.AreEqual(currentRowCount, result.RowsAffected, "We should have duplicated the amount of rows");
            }
        }
コード例 #44
0
        public void BasicSelectTest()
        {
            var   db    = new Database();
            Table table = db.AddTable("TBL");

            table.AddColumn(new Column("ID", typeof(int)));

            var row = table.NewRow(3);

            table.AddRow(row);

            string         query       = "Select * from [TBL]";
            SQLInterpreter interpreter = new SQLInterpreter(db);

            var result   = interpreter.Execute(query)[0];
            int affected = result.RowsAffected;

            Assert.AreEqual(1, affected, "There should be one row affected");
            Assert.AreEqual(3, result.Values.Records.First()["ID"], "The selected value was not present on the Table");
        }
コード例 #45
0
ファイル: ColumnsBinder.cs プロジェクト: ImanRezaeipour/GTS
        private void BindColumn(HbmColumn hbmColumn, Table table, bool isNullable)
        {
            var col = new Column {
                Value = value
            };

            BindColumn(hbmColumn, col, isNullable);

            if (table != null)
            {
                table.AddColumn(col);
            }

            value.AddColumn(col);

            //column index
            BindIndex(hbmColumn.index, table, col);
            //column group index (although it can serve as a separate column index)
            BindUniqueKey(hbmColumn.uniquekey, table, col);
        }
コード例 #46
0
ファイル: DeletionTests.cs プロジェクト: IM-SQL/IMSQL
        public void TopDeleteTest()
        {
            var   db    = new Database();
            Table table = db.AddTable("TBL");

            table.AddColumn(new Column("ID", typeof(int)));
            for (int i = 0; i < 200; i++)
            {
                var row = table.NewRow(i);
                table.AddRow(row);
            }
            string         query       = "Delete TOP(50) from [TBL]";
            SQLInterpreter interpreter = new SQLInterpreter(db);

            var result   = interpreter.Execute(query)[0];
            int affected = result.RowsAffected;

            Assert.AreEqual(50, affected, "There should be 50 row affected");
            Assert.AreEqual(150, table.Rows.Count(), "There should be 150 rows on the table");
        }
コード例 #47
0
ファイル: DeletionTests.cs プロジェクト: IM-SQL/IMSQL
        public void DeleteWhereOr()
        {
            var   db    = new Database();
            Table table = db.AddTable("TBL");

            table.AddColumn(new Column("ID", typeof(int)));
            for (int i = 0; i < 100; i++)
            {
                var row = table.NewRow(i);
                table.AddRow(row);
            }
            string         query       = "Delete from [TBL] where [ID] < 1 OR [ID] > 98";
            SQLInterpreter interpreter = new SQLInterpreter(db);

            var result   = interpreter.Execute(query)[0];
            int affected = result.RowsAffected;

            Assert.AreEqual(2, affected, "There should be 2 row affected");
            Assert.AreEqual(98, table.Rows.Count(), "There should be 98 rows on the table");
        }
コード例 #48
0
        public Task Should_Render_Table_With_Cell_Padding_Correctly()
        {
            // Given
            var console = new FakeConsole(width: 80);
            var table   = new Table();

            table.AddColumns("Foo", "Bar");
            table.AddColumn(new TableColumn("Baz")
            {
                Padding = new Padding(3, 0, 2, 0)
            });
            table.AddRow("Qux\nQuuux", "Corgi", "Waldo");
            table.AddRow("Grault", "Garply", "Fred");

            // When
            console.Write(table);

            // Then
            return(Verifier.Verify(console.Output));
        }
コード例 #49
0
        public IDictionary <string, Table> GetTables()
        {
            var result = new Dictionary <string, Table>();

            using (var connection = CreateConnection())
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = GeneratorSelectText();
                    connection.Open();
                    var reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        var tableName  = reader["TableName"].ToString();
                        var columnName = reader["ColumnName"].ToString();
                        if (this.Option.Ignores == null || this.Option.Ignores.Contains(columnName))
                        {
                            continue;
                        }
                        var column = new Column
                        {
                            Name       = columnName,
                            DataType   = reader["DataType"].ToString(),
                            Position   = int.Parse(reader["Position"].ToString()),
                            CanBeNull  = reader["CanBeNull"].ToString() == "1",
                            CharLength = int.Parse(reader["CharLength"].ToString()),
                            Comment    = reader["Comment"].ToString()
                        };
                        if (result.ContainsKey(tableName))
                        {
                            result[tableName].AddColumn(column);
                        }
                        else
                        {
                            var table = new Table(tableName);
                            table.AddColumn(column);
                            result[tableName] = table;
                        }
                    }
                }
            return(result);
        }
コード例 #50
0
        public void Should_Render_Table_Without_Footer_If_No_Rows_Are_Added()
        {
            // Given
            var console = new PlainConsole(width: 80);
            var table   = new Table();

            table.AddColumns("Foo", "Bar");
            table.AddColumn(new TableColumn("Baz")
            {
                Padding = new Padding(3, 0, 2, 0)
            });

            // When
            console.Render(table);

            // Then
            console.Lines.Count.ShouldBe(3);
            console.Lines[0].ShouldBe("┌─────┬─────┬────────┐");
            console.Lines[1].ShouldBe("│ Foo │ Bar │   Baz  │");
            console.Lines[2].ShouldBe("└─────┴─────┴────────┘");
        }
コード例 #51
0
        public void Setup()
        {
            database = new Database("Db1");
            entitySet = new EntitySetImpl();

            table = new Table("Table1");
            table.AddColumn(new Column("Column1"));
            entity1 = new EntityImpl("Entity1");
            entity1.AddProperty(new PropertyImpl("Property1"));
            entity2 = new EntityImpl("Entity2");

            entity2.AddProperty(new PropertyImpl("Property2"));
            var reference = entity1.CreateReferenceTo(entity2);
            reference.Identifier = new Guid("11111111-1111-1111-1111-111111111111");
            reference.End1Name = "end1";
            reference.End2Name = "end2";
            entitySet.AddReference(reference);

            database.AddTable(table);
            entitySet.AddEntity(entity1);
        }
コード例 #52
0
ファイル: DeletionTests.cs プロジェクト: IM-SQL/IMSQL
        public void BasicDeleteTest()
        {
            var   db    = new Database();
            Table table = db.AddTable("TBL");

            table.AddColumn(new Column("ID", typeof(int)));

            var row = table.NewRow(3);

            table.AddRow(row);

            string         query       = "Delete from [TBL]";
            SQLInterpreter interpreter = new SQLInterpreter(db);

            var result   = interpreter.Execute(query)[0];
            int affected = result.RowsAffected;

            Assert.AreEqual(1, affected, "There should be one row affected");
            Assert.AreEqual(0, table.Rows.Count(), "There should be no rows on the table");
            Assert.IsTrue(row.RowState == DataRowState.Detached, "The created row should have been detached because it is no longer in the table");
        }
コード例 #53
0
        public static Table CreateFullTable(string tableName, List <Column> columns, List <List <string> > cellData)
        {
            Table table = new Table(tableName);

            for (int i = 0; i < columns.Count; i++)
            {
                table.AddColumn(columns[i]);
            }
            Row row;

            for (int i = 0; i < cellData.Count; i++)
            {
                row = table.CreateRowDefinition();
                for (int j = 0; j < cellData[i].Count; j++)
                {
                    row.SetCellValue(columns[j].columnName, cellData[i][j]);
                }
                table.AddRow(row);
            }
            return(table);
        }
コード例 #54
0
ファイル: CMigraDoc.cs プロジェクト: mcarmona/Git-Repo
        /// <summary>
        /// Add a New Column to the table, after you have added the first row with the "AddFirstColumn" method
        /// </summary>
        /// <param name="pTable">Table in wich the table is going to be added</param>
        /// <param name="pWidth">Width of the new Column</param>
        /// <param name="pAlignment">How the text is going to be presented, centered, justified, left or right</param>
        public void AddColumn(Table pTable, double pWidth, int pAlignment)
        {
            pTable.AddColumn(Unit.FromCentimeter(pWidth));

            if (pAlignment == 0)
            {
                column.Format.Alignment = ParagraphAlignment.Left;
            }
            else if (pAlignment == 1)
            {
                column.Format.Alignment = ParagraphAlignment.Center;
            }
            else if (pAlignment == 2)
            {
                column.Format.Alignment = ParagraphAlignment.Right;
            }
            else if (pAlignment == 3)
            {
                column.Format.Alignment = ParagraphAlignment.Justify;
            }
        }
コード例 #55
0
            public void The_Original_Database_Should_Contain_A_Copy_Of_The_New_Table()
            {
                var db1 = TestDatabaseLoader.TestDatabase();

                Table newTable = new Table("Table2");
                Column newColumn = new Column("Column1");
                Key newKey = new Key("PrimaryKey");
                Index newIndex = new Index("Index1");
                newTable.AddColumn(newColumn);
                newTable.AddKey(newKey);
                newTable.AddIndex(newIndex);

                TableAdditionOperation op = new TableAdditionOperation(db1, newTable);
                op.RunOperation();

                Assert.That(db1.Tables, Has.Count(2));
                Assert.That(db1.Tables[1].Name, Is.EqualTo(newTable.Name));
                Assert.That(db1.Tables[1], Is.Not.SameAs(newTable), "The added table should be a copy, not the original object.");
                Assert.That(db1.Tables[1].Columns[0], Is.EqualTo(newColumn));
                Assert.That(db1.Tables[1].Keys[0], Is.EqualTo(newKey));
                Assert.That(db1.Tables[1].Indexes[0], Is.EqualTo(newIndex));
            }
        public void It_Should_Serialise_To_This()
        {
            XmlNode root = When_Serialising_A_Discriminator_With_One_Condition.FullDiscriminatorXml.GetXmlDocRoot();
            Entity entity = new EntityImpl("Entity1");

            var column = new Column("Column1");
            Table table = new Table("Table1");
            table.AddColumn(column);
            var database = new Database("db1");
            database.AddTable(table);

            var dis = new EntitySetDeserialisationScheme().DeserialiseDiscriminator(root, database);

            Assert.That(dis, Is.Not.Null);
            Assert.That(dis.RootGrouping, Is.Not.Null);
            Assert.That(dis.RootGrouping.ContainsConditions, Is.True);
            Assert.That(dis.RootGrouping.ContainsGroupings, Is.False);

            var condition = dis.RootGrouping.Conditions.ElementAt(0);

            Assert.That(condition.Column, Is.SameAs(column));
            Assert.That(condition.Operator, Is.SameAs(Operator.Equal));
            Assert.That(condition.ExpressionValue.Value, Is.EqualTo("5"));
        }
        internal static Database GetDb()
        {
            var db = TestDatabaseLoader.TestDatabase();
            Table table2 = new Table("Table2");
            table2.AddColumn(new Column("Column1"));
            table2.AddColumn(new Column("Column2"));
            table2.AddColumn(new Column("Column3"));
            Key foreignKey = new Key("FK_Table2", DatabaseKeyType.Foreign);
            foreignKey.Parent = table2;
            foreignKey.ReferencedKey = db.Tables[0].Keys[0];
            foreignKey.AddColumn("Column1");
            foreignKey.AddColumn("Column2");
            table2.AddKey(foreignKey);
            db.AddTable(table2);

            new DatabaseProcessor().CreateRelationships(db);
            return db;
        }
コード例 #58
0
        public void Setup()
        {
            // Setup Database
            database = new Database("DB1");
            var table = new Table("User");
            table.AddColumn(new Column("Name"));
            table.AddColumn(new Column("AddressStreet"));
            table.AddColumn(new Column("AddressCity"));
            table.AddColumn(new Column("AddressCountry"));
            database.AddTable(table);

            // Setup Entities
            entitySet = new EntitySetImpl();
            Entity userEntity = new EntityImpl("User");
            userEntity.AddProperty(new PropertyImpl("Name"));

            // Create the Address type
            spec = new ComponentSpecificationImpl("Address");

            spec.AddProperty(new ComponentPropertyImpl("Street"));
            spec.AddProperty(new ComponentPropertyImpl("City"));
            spec.AddProperty(new ComponentPropertyImpl("Country"));

            // Create the Address component for the User entity.
            component = spec.CreateImplementedComponentFor(userEntity, "HomeAddress");

            entitySet.AddEntity(userEntity);
            entitySet.AddComponentSpecification(spec);

            // Setup the Mappings
            mappingSet = new MappingSetImpl(database, entitySet);
            componentMapping = new ComponentMappingImpl();
            mappingSet.AddMapping(componentMapping);

            componentMapping.AddPropertyAndColumn(component.Properties[0], table.Columns[1]);
            componentMapping.AddPropertyAndColumn(component.Properties[1], table.Columns[2]);
            componentMapping.AddPropertyAndColumn(component.Properties[2], table.Columns[3]);

            // Add the mapping between the Name property and the Name column in the database table.
            mappingSet.ChangeMappedColumnFor(userEntity.ConcreteProperties[0]).To(table.Columns[0]);
        }
コード例 #59
0
        public void Process()
        {
            PreProcess();

            #region Variables
            List<string> entityHadCreated = new List<string>();
            #endregion

            #region EERD
            foreach (SubTypeConnectorData st in erd.SubTypeConnectors)
            {
                string supperTypeName = st.SuperType;
                List<string> listSubTypeName = new List<string>();
                List<string> listDiscriminators = new List<string>();
                foreach (string sub in st.SubTypes)
                    listSubTypeName.Add(sub);
                foreach (string dis in st.Discriminators)
                    listDiscriminators.Add(dis);

                //Tạo Table SupperType
                if (!SearchInList(entityHadCreated, supperTypeName))
                {
                    EntityData entityData = SearchEntityData(supperTypeName);
                    mdp.ConvertEntityStrongToTable(entityData);
                    entityHadCreated.Add(supperTypeName);
                }

                //Tạo Table SubType
                foreach (string subTypeName in listSubTypeName)
                {
                    if (!SearchInList(entityHadCreated, subTypeName))
                    {
                        EntityData subEntity = SearchEntityData(subTypeName);
                        mdp.ConvertEntityStrongToTable(subEntity);
                        entityHadCreated.Add(subTypeName);
                    }
                }

                //Add thuộc tính SupperType vào SubType
                Table supperTable = mdp.SearchTable(supperTypeName);
                List<Column> listPK = supperTable.GetPrimaryKey();

                for (int i = 0; i < listSubTypeName.Count; i++)
                {
                    string subTypeName = listSubTypeName[i];
                    Table subTable = mdp.SearchTable(subTypeName);
                    if (st.Discriminators.Count > 0)
                    {
                        List<Column> listPkNew = new List<Column>();
                        foreach (Column c in listPK)
                        {
                            Column tempColumn = new Column();
                            tempColumn.Name = listDiscriminators[i].ToUpper() + "_" + c.Name;
                            tempColumn.DataType = c.DataType;
                            tempColumn.Length = c.Length;
                            tempColumn.AlowNull = c.AlowNull;
                            tempColumn.Description = c.Description;
                            tempColumn.PrimaryKey = c.PrimaryKey;
                            tempColumn.ForeignKey = c.ForeignKey;
                            listPkNew.Add(tempColumn);
                        }
                        subTable.AddPrimaryKeyForeignKey(listPkNew);
                    }
                    else
                        subTable.AddPrimaryKeyForeignKey(listPK);
                    mdp.AddForeignKey("fk_" + supperTypeName, supperTable, listPK, subTable, listPK);
                }
            }
            #endregion

            #region Entities
            foreach (EntityData ed in erd.Entities)
            {
                //Kiểm tra coi Entity thuộc loại nào
                //Tiến hành xử lý , Entity Strong, Entity Weak
                //Entity Strong: Normal, Has Composite Attribute, Has MultiValue Attribute.

                #region EntityStrong
                if (ed.type == EntityType.Strong)//Entity Strong
                {
                    //Kiểm tra Entity này tạo thành Table chưa, nếu chưa mới thực hiện
                    if (!SearchInList(entityHadCreated, ed.name))
                    {
                        mdp.ConvertEntityStrongToTable(ed);
                        entityHadCreated.Add(ed.name);
                    }
                }
                #endregion

                #region EntityWeak
                if (ed.type == EntityType.Weak)//Entity Weak
                {

                    string nEntityWeak = ed.name;
                    string nEntityParent = SearchEntityParent(nEntityWeak);

                    //Kiểm tra xem thằng Parent có tồn tại hay chưa
                    //Nếu chưa thì phải tạo Parent trước
                    //Sau đó tạo Weak

                    if (!SearchInList(entityHadCreated, nEntityParent))
                    {
                        EntityData parentEntity = SearchEntityData(nEntityParent);
                        mdp.ConvertEntityStrongToTable(parentEntity);
                        entityHadCreated.Add(nEntityParent);
                    }

                    Table weakTable = new Table(ed.name, ed.x, ed.y, ed.w, ed.h);
                    Table parentTable = mdp.SearchTable(nEntityParent);

                    AttributeData multiAttribute = new AttributeData();
                    //Process Column
                    foreach (AttributeData ad in ed.Attributes)
                    {
                        //Composite Attribute
                        if (ad.AttributeChilds.Count > 0)
                        {
                            bool isTypeColumn = false;//False->Simple, True->Key
                            if (ad.type == AttributeType.Key)
                                isTypeColumn = true;
                            if (ad.type == AttributeType.Simple)
                                isTypeColumn = false;
                            foreach (AttributeData ac in ad.AttributeChilds)
                            {
                                if (!isTypeColumn)//Simple
                                    weakTable.AddColumn(ac);
                                if (isTypeColumn)//PK
                                    weakTable.AddPrimaryKey(ac.name, ac.DataType, ac.Length, ac.Description);
                            }
                        }
                        //Key, Simple, Multi Attribute
                        else
                        {
                            switch (ad.type)
                            {
                                case AttributeType.Key:
                                    weakTable.AddPrimaryKey(ad.name, ad.DataType, ad.Length, ad.Description);
                                    break;
                                case AttributeType.Simple:
                                    weakTable.AddColumn(ad);
                                    break;
                                //Chưa xử lý chỉ gắn tạm thời trường hợp đa trị
                                case AttributeType.MultiValued:
                                    multiAttribute = ad;
                                    break;
                            }
                        }
                    }

                    //Chuyển PK bảng Parent thành FK bảng Weak
                    List<Column> pkParent = parentTable.GetPrimaryKey();
                    weakTable.AddPrimaryKeyForeignKey(pkParent);
                    //Add bảng Weak vào MetaDataPhysical
                    mdp.AddTable(weakTable);
                    //Tạo quan hệ khóa ngoại cho bảng Parent và Weak
                    mdp.AddForeignKey("fk_" + parentTable.name, parentTable, pkParent, weakTable, pkParent);

                    //Xử lý Weak có thuộc tính đa trị
                    if (multiAttribute.name != String.Empty)
                        EntityHasMultivalueAttribute(weakTable, multiAttribute);
                }
                #endregion
            }//End Entities

            #endregion

            #region Relationships
            foreach (RelationshipData rd in erd.Relationships)
            {
                //Lấy Name Relationship , Type Cardinality
                //Xét xem nằm loại nào : 1-n , n-n, 1-1.
                string cardinalityMin1 = "";
                string cardinalityMax1 = "";
                string nameTable1 = "";

                string cardinalityMin2 = "";
                string cardinalityMax2 = "";
                string nameTable2 = "";

                string cardinalityMin3 = "";
                string cardinalityMax3 = "";
                string nameTable3 = "";

                string nameRelationship = rd.name;

                //Duyệt lấy các giá trị của 1 Relationship
                for (int i = 0; i < rd.Cardinalities.Count; i++)
                {
                    if (i == 0)
                    {
                        cardinalityMin1 = rd.Cardinalities[i].MinCardinality.ToString();
                        cardinalityMax1 = rd.Cardinalities[i].MaxCardinality.ToString();
                        nameTable1 = rd.Cardinalities[i].Entity;
                    }
                    else
                    {
                        if (i == 1)
                        {
                            cardinalityMin2 = rd.Cardinalities[i].MinCardinality.ToString();
                            cardinalityMax2 = rd.Cardinalities[i].MaxCardinality.ToString();
                            nameTable2 = rd.Cardinalities[i].Entity;
                        }
                        else
                        {
                            if (i == 2)
                            {
                                cardinalityMin3 = rd.Cardinalities[i].MinCardinality.ToString();
                                cardinalityMax3 = rd.Cardinalities[i].MaxCardinality.ToString();
                                nameTable3 = rd.Cardinalities[i].Entity;
                            }
                        }
                    }
                }

                #region Trường hợp 1 ngôi
                if (rd.Cardinalities.Count == 2 && nameTable1 == nameTable2)
                {
                    //Trường hợp 1:n, n:1
                    if ((cardinalityMax1 == "1" && cardinalityMax2 == "-1") || (cardinalityMax1 == "-1" && cardinalityMax2 == "1") || (cardinalityMax1 == "1" && cardinalityMax2 == "1") || (cardinalityMax1 == "0" && cardinalityMax2 == "1") || (cardinalityMax1 == "1" && cardinalityMax2 == "0"))
                    {
                        Table t1 = mdp.SearchTable(nameTable1);
                        List<Column> pk1 = t1.GetPrimaryKey();

                        if (rd.Attributes.Count > 0)
                        {
                            foreach (AttributeData adChild in rd.Attributes)
                            {
                                if (adChild.AttributeChilds.Count > 0)//Compsite
                                {
                                    foreach (AttributeData var in adChild.AttributeChilds)
                                        t1.AddColumn(adChild);
                                }
                                else//Simple
                                    if (adChild.type == AttributeType.Simple)
                                        t1.AddColumn(adChild);
                            }
                        }//end if
                        List<Column> listFK = new List<Column>();
                        for (int i = 0; i < pk1.Count; i++)
                        {
                            Column col = new Column();
                            col.AlowNull = pk1[i].AlowNull;
                            col.DataType = pk1[i].DataType;
                            col.Length = pk1[i].Length;
                            col.PrimaryKey = pk1[i].PrimaryKey;
                            col.ForeignKey = pk1[i].ForeignKey;
                            if (i > 0)
                                col.Name = nameRelationship + "_" + i;
                            else
                                col.Name = nameRelationship;
                            listFK.Add(col);
                        }
                        t1.AddColumnFK(listFK);
                        mdp.AddForeignKey(nameRelationship, t1, pk1, t1, listFK);
                    }

                    //Trường hợp n:n
                    if (cardinalityMax1 == "-1" && cardinalityMax2 == "-1")
                    {
                        Table t1 = mdp.SearchTable(nameTable1);
                        List<Column> pk1 = t1.GetPrimaryKey();

                        Table t2 = new Table(nameRelationship, rd.x, rd.y, rd.w, rd.h);

                        AttributeData multiAttribute = new AttributeData();
                        t2.AddPrimaryKeyForeignKey(pk1);
                        List<Column> pk2 = new List<Column>();
                        for (int i = 0; i < pk1.Count; i++)
                        {
                            Column c = new Column(pk1[i].Name + "_" + i, pk1[i].DataType, pk1[i].Length, pk1[i].AlowNull, pk1[i].PrimaryKey, pk1[i].ForeignKey, pk1[i].Description);
                            pk2.Add(c);
                        }
                        t2.AddPrimaryKeyForeignKey(pk2);

                        //Add tất cả các Attribute có trên thuộc tính vào bên bản mới sinh
                        if (rd.Attributes.Count > 0)
                        {
                            foreach (AttributeData adChild in rd.Attributes)
                            {
                                if (adChild.AttributeChilds.Count > 0)//Compsite
                                {
                                    foreach (AttributeData var in adChild.AttributeChilds)
                                        t2.AddColumn(adChild);
                                }
                                else//Simple
                                {
                                    if (adChild.type == AttributeType.Simple)
                                        t2.AddColumn(adChild);

                                    if (adChild.type == AttributeType.MultiValued)
                                        multiAttribute = adChild;

                                    if (adChild.type == AttributeType.Key)
                                        t2.AddPrimaryKey(adChild.name, adChild.DataType, adChild.Length, adChild.Description);
                                }

                            }
                        }//end if
                        mdp.AddTable(t2);
                        mdp.AddForeignKey(nameRelationship + "_1", t1, pk1, t2, pk1);
                        mdp.AddForeignKey(nameRelationship + "_2", t1, pk1, t2, pk2);

                        //Xử lý trường hớp có multivalue attribute
                        if (multiAttribute.name != String.Empty)
                        {
                            EntityHasMultivalueAttribute(t2, multiAttribute);
                        }
                    }
                }//End 1 ngôi
                #endregion

                #region Trường hợp 2 ngôi
                if (rd.Cardinalities.Count == 2 && nameTable1 != nameTable2)
                {
                    #region Normal Relationship
                    //Trường hợp relationship bình thường
                    if (rd.type == RelationshipType.Normal)
                    {
                        //TH 1:n
                        if (cardinalityMax1 == "1" && cardinalityMax2 == "-1")
                        {
                            //Tìm table tren MDP
                            //them coloum vao` table
                            //tao Relationship
                            //Them Relationship vao

                            Table t1 = mdp.SearchTable(nameTable1);//Bảng một
                            Table t2 = mdp.SearchTable(nameTable2);//Bảng nhiều

                            List<Column> pkT1 = t1.GetPrimaryKey();
                            t2.AddColumnFK(pkT1);

                            if (rd.Attributes.Count > 0)
                            {
                                //Thiếu trường hợp Multivalue
                                foreach (AttributeData ad in rd.Attributes)
                                {
                                    //Simple Attribute
                                    if (ad.type == AttributeType.Simple && ad.AttributeChilds.Count == 0)
                                        t2.AddColumn(ad);

                                    //Composite Attribute
                                    if (ad.AttributeChilds.Count > 0)
                                    {
                                        foreach (AttributeData adChild in ad.AttributeChilds)
                                            t2.AddColumn(adChild);
                                    }
                                }
                            }
                            mdp.AddForeignKey(nameRelationship, t1, pkT1, t2, pkT1);
                        }
                        //TH n,1
                        if (cardinalityMax1 == "-1" && cardinalityMax2 == "1")
                        {
                            Table t1 = mdp.SearchTable(nameTable2);//Bảng một
                            Table t2 = mdp.SearchTable(nameTable1);//Bảng nhiều

                            List<Column> pkT1 = t1.GetPrimaryKey();
                            t2.AddColumnFK(pkT1);

                            if (rd.Attributes.Count > 0)
                            {
                                //Thiếu trường hợp Multivalue
                                foreach (AttributeData ad in rd.Attributes)
                                {
                                    //Simple Attribute
                                    if (ad.type == AttributeType.Simple && ad.AttributeChilds.Count == 0)
                                        t2.AddColumn(ad);

                                    //Composite Attribute
                                    if (ad.AttributeChilds.Count > 0)
                                    {
                                        foreach (AttributeData adChild in ad.AttributeChilds)
                                            t2.AddColumn(adChild);
                                    }
                                }
                            }
                            mdp.AddForeignKey(nameRelationship, t1, pkT1, t2, pkT1);
                        }
                        //TH n:n
                        if (cardinalityMax1 == "-1" && cardinalityMax2 == "-1")
                        {
                            //Tìm Table tren MDP
                            //Create table trung gian (Relasionship)
                            //Tạo khóa chính gồm 2 khóa.
                            //Thêm vào MDP
                            //Tạo 2 fk vào MDP
                            Table t1 = mdp.SearchTable(nameTable1);
                            Table t2 = mdp.SearchTable(nameTable2);

                            List<Column> pk1 = t1.GetPrimaryKey();
                            List<Column> pk2 = t2.GetPrimaryKey();

                            Table temp = new Table(nameRelationship.ToUpper(), rd.x, rd.y, rd.w, rd.h);

                            temp.AddPrimaryKeyForeignKey(pk1);
                            temp.AddPrimaryKeyForeignKey(pk2);

                            if (rd.Attributes.Count > 0)
                            {
                                //Thiếu trường hợp Multivalue
                                foreach (AttributeData ad in rd.Attributes)
                                {
                                    //Simple Attribute
                                    if (ad.type == AttributeType.Simple && ad.AttributeChilds.Count == 0)
                                        temp.AddColumn(ad);
                                    //Composite Attribute
                                    if (ad.AttributeChilds.Count > 0)
                                    {
                                        foreach (AttributeData adChild in ad.AttributeChilds)
                                            temp.AddColumn(adChild);
                                    }
                                }
                            }
                            mdp.AddTable(temp);
                            mdp.AddForeignKey(nameRelationship, t1, pk1, temp, pk1);
                            mdp.AddForeignKey(nameRelationship, t2, pk2, temp, pk2);
                        }
                        //TH 1,1
                        if (cardinalityMax1 == "1" && cardinalityMax2 == "1")
                        {
                            //TH 0:1
                            if (cardinalityMin1 == "0" && cardinalityMin2 == "1")
                            {
                                Table t1 = mdp.SearchTable(nameTable2);//Bảng 1
                                Table t2 = mdp.SearchTable(nameTable1);//Bảng 0

                                List<Column> pk1 = t1.GetPrimaryKey();
                                if (rd.Attributes.Count > 0)
                                {
                                    foreach (AttributeData ad in rd.Attributes)
                                    {
                                        //Simple Attribute
                                        if (ad.type == AttributeType.Simple && ad.AttributeChilds.Count == 0)
                                            t2.AddColumn(ad);
                                        //Composite Attribute
                                        if (ad.AttributeChilds.Count > 0)
                                        {
                                            foreach (AttributeData adChild in ad.AttributeChilds)
                                                t2.AddColumn(adChild);
                                        }
                                    }
                                }
                                //Chuyển PK bảng 1 thành FK bảng 0
                                t2.AddColumnFK(pk1);
                                mdp.AddForeignKey(nameRelationship, t1, pk1, t2, pk1);
                            }
                            //TH 1:0
                            if (cardinalityMin2 == "0" && cardinalityMin1 == "1")
                            {
                                Table t1 = mdp.SearchTable(nameTable1);//Bảng 1
                                Table t2 = mdp.SearchTable(nameTable2);//Bảng 0

                                List<Column> pk1 = t1.GetPrimaryKey();
                                if (rd.Attributes.Count > 0)
                                {
                                    foreach (AttributeData ad in rd.Attributes)
                                    {
                                        //Simple Attribute
                                        if (ad.type == AttributeType.Simple && ad.AttributeChilds.Count == 0)
                                            t2.AddColumn(ad);
                                        //Composite Attribute
                                        if (ad.AttributeChilds.Count > 0)
                                        {
                                            foreach (AttributeData adChild in ad.AttributeChilds)
                                                t2.AddColumn(adChild);
                                        }
                                    }
                                }
                                //Chuyển PK bảng 1 thành FK bảng 0
                                t2.AddColumnFK(pk1);
                                mdp.AddForeignKey(nameRelationship, t1, pk1, t2, pk1);
                            }
                            //Trường hợp 1:1
                            if ((cardinalityMin1 == "1" && cardinalityMin2 == "1") || (cardinalityMin1 == "0" && cardinalityMin2 == "0"))
                            {
                                Table t1 = mdp.SearchTable(nameTable1);//Bảng 1
                                Table t2 = mdp.SearchTable(nameTable2);//Bảng 0

                                List<Column> pk1 = t1.GetPrimaryKey();
                                if (rd.Attributes.Count > 0)
                                {
                                    foreach (AttributeData ad in rd.Attributes)
                                    {
                                        //Simple Attribute
                                        if (ad.type == AttributeType.Simple && ad.AttributeChilds.Count == 0)
                                            t2.AddColumn(ad);
                                        //Composite Attribute
                                        if (ad.AttributeChilds.Count > 0)
                                        {
                                            foreach (AttributeData adChild in ad.AttributeChilds)
                                                t2.AddColumn(adChild);
                                        }
                                    }
                                }
                                //Chuyển PK bảng 1 thành FK bảng 0
                                t2.AddColumnFK(pk1);
                                mdp.AddForeignKey(nameRelationship, t1, pk1, t2, pk1);
                            }
                        }
                    }//End Normal Relationship
                    #endregion

                    #region Associative Entity
                    //Trường hợp Associative Entity
                    if (rd.type == RelationshipType.AssociativeEntity)
                    {

                        //Nếu có khóa chính thì Add 2 key quan hệ là FK
                        //Không có khóa chính thì tạo Compsite Key từ 2 entity quan hệ

                        Table t1 = mdp.SearchTable(nameTable1);
                        Table t2 = mdp.SearchTable(nameTable2);

                        List<Column> pk1 = t1.GetPrimaryKey();
                        List<Column> pk2 = t2.GetPrimaryKey();

                        bool hasPK = false;
                        foreach (AttributeData ad in rd.Attributes)
                        {
                            if (ad.type == AttributeType.Key)
                            {
                                hasPK = true;
                                break;
                            }
                        }
                        //Tạo Entity Data từ Associative Entity
                        EntityData edTemp = new EntityData(rd.name.ToUpper(), EntityType.Strong, rd.x, rd.y, rd.w, rd.h);

                        if (!hasPK)//Assocaitive Entity ko có PK
                        {
                            foreach (Column col1 in pk1)
                                edTemp.Attributes.Add(new AttributeData(col1.Name, AttributeType.Key, 0, 0, 0, 0, col1.DataType, col1.Length, col1.AlowNull, col1.Description));
                            foreach (Column col2 in pk2)
                                edTemp.Attributes.Add(new AttributeData(col2.Name, AttributeType.Key, 0, 0, 0, 0, col2.DataType, col2.Length, col2.AlowNull, col2.Description));

                        }

                        foreach (AttributeData ad in rd.Attributes)
                        {
                            AttributeData adTemp = new AttributeData();
                            //Xét Associative Enity có Composite Attribute
                            if (ad.AttributeChilds.Count > 0)
                            {
                                adTemp = new AttributeData(ad.name, ad.type, ad.x, ad.y, ad.w, ad.h, ad.DataType, ad.Length, ad.AllowNull, ad.Description);
                                adTemp.isComposite = true;
                                foreach (AttributeData adChild in ad.AttributeChilds)
                                    adTemp.AttributeChilds.Add(adChild);
                            }
                            else
                                adTemp = new AttributeData(ad.name, ad.type, ad.x, ad.y, ad.w, ad.h, ad.DataType, ad.Length, ad.AllowNull, ad.Description);
                            edTemp.Attributes.Add(adTemp);
                        }

                        mdp.ConvertEntityStrongToTable(edTemp);

                        //Lấy Table Associative vừa tạo
                        Table temp = mdp.SearchTable(edTemp.name);

                        if (!hasPK)//Không có PK, thì 2 khóa chính từ 2 bảng quan hệ chuyển thành PK,FK
                        {
                            foreach (Column col in temp.columns)
                                if (col.PrimaryKey)
                                    col.IsPrimaryKeyForeignKey();
                        }
                        else//Có khóa, thì 2 List PK1, PK2 của 2 bảng quan hệ được add vào Temp (bảng Associative)
                        {
                            temp.AddColumnFK(pk1);
                            temp.AddColumnFK(pk2);
                        }

                        mdp.AddForeignKey("", t1, pk1, temp, pk1);
                        mdp.AddForeignKey("", t2, pk2, temp, pk2);

                    }//End Associative Entity
                    #endregion
                }//End TH 2 ngôi
                #endregion

                #region Trường hợp 3 ngôi
                if (rd.Cardinalities.Count == 3)
                {
                    //Relationship Normal:1-1-1, 1-1-n, 1-n-m, n-m-l

                    Table t1 = mdp.SearchTable(nameTable1);
                    Table t2 = mdp.SearchTable(nameTable2);
                    Table t3 = mdp.SearchTable(nameTable3);

                    if (rd.type == RelationshipType.Normal)
                    {
                        //TH 1-1-1
                        if (cardinalityMax1 == "1" && cardinalityMax2 == "1" && cardinalityMax3 == "1")
                            ProcessTernary(rd, nameRelationship, t1, t2, t3);

                        //TH 1-1-n
                        if (cardinalityMax1 == "1" && cardinalityMax2 == "1" && cardinalityMax3 == "-1")
                            ProcessTernary(rd, nameRelationship, t3, t2, t1);

                        //TH 1-n-1
                        if (cardinalityMax1 == "1" && cardinalityMax2 == "-1" && cardinalityMax3 == "1")
                            ProcessTernary(rd, nameRelationship, t2, t1, t3);

                        //TH n-1-1
                        if (cardinalityMax1 == "-1" && cardinalityMax2 == "1" && cardinalityMax3 == "1")
                            ProcessTernary(rd, nameRelationship, t1, t2, t3);

                        //TH 1-n-m
                        if (cardinalityMax1 == "1" && cardinalityMax2 == "-1" && cardinalityMax3 == "-1")
                            ProcessTernary(rd, nameRelationship, t2, t3, t1);

                        //TH n-1-m
                        if (cardinalityMax1 == "-1" && cardinalityMax2 == "1" && cardinalityMax3 == "-1")
                            ProcessTernary(rd, nameRelationship, t1, t3, t1);

                        //TH n-m-1
                        if (cardinalityMax1 == "-1" && cardinalityMax2 == "-1" && cardinalityMax3 == "1")
                            ProcessTernary(rd, nameRelationship, t1, t2, t3);

                        //TH n-m-l
                        if (cardinalityMax1 == "-1" && cardinalityMax2 == "-1" && cardinalityMax3 == "-1")
                            ProcessTernary(rd, nameRelationship, t1, t2, t3, true);

                    }//End IF

                    //Relationship Associate
                    if (rd.type == RelationshipType.AssociativeEntity)
                    {
                        //xảy ra hai trường hợp
                        //TH1: không có khóa chính - tương tự như trường hợp n-m-l
                        //TH2: có khóa chính - lấy khóa chính, và còn lại là khóa ngoại
                        ProcessTernary(rd, nameRelationship, t1, t2, t3, true);
                    }
                }
                #endregion

            }//End Relationships
            #endregion
        }
コード例 #60
0
        /// <summary>
        /// Xử lý các trường hợp mối liên kết ba ngôi: 1-1-1, 1-1-n, 1-n-m, n-m-l, associative entity
        /// Lưu ý: Thứ tự t1,t2,t3 ảnh hưởng/tác dụng tới từng trường hợp cụ thể
        ///     1-1-1: t1,t2,t3   |   
        ///     1-1-n: t3,t1,t2   |   
        ///     1-n-1: t2,t1,t3   |   
        ///     n-1-1: t1,t2,t3   |   
        ///     1-n-m: t2,t3,t1   |   
        ///     n-1-m: t1,t3,t2   |   
        ///     n-m-1: t1,t2,t3   |   
        ///     n-m-l: t1,t2,t3,true   |   
        ///     associative entity: t1,t2,t3,true   |   
        /// </summary>
        /// <param name="t1">Table 1 trong Relationship Ternary</param>
        /// <param name="t2">Table 2 trong Relationship Ternary</param>
        /// <param name="t3">Table 3 trong Relationship Ternary</param>
        /// <param name="f"> default : FALSE, f = true trường hợp n-m-l, f = false các trường hợp còn lại</param>        
        private void ProcessTernary(RelationshipData rd, string nameRelationship, Table t1, Table t2, Table t3, bool f)
        {
            List<Column> pk1 = t1.GetPrimaryKey();
            List<Column> pk2 = t2.GetPrimaryKey();
            List<Column> pk3 = t3.GetPrimaryKey();

            bool hasPrimaryKey = false;

            Table t4 = new Table(nameRelationship, rd.x, rd.y, rd.w, rd.h);
            AttributeData mulAttribute = new AttributeData();
            foreach (AttributeData ad in rd.Attributes)
            {
                //Composite Attribute
                if (ad.AttributeChilds.Count > 0)
                {
                    foreach (AttributeData adChild in ad.AttributeChilds)
                        t4.AddColumn(adChild);
                }
                else
                {
                    if (ad.type == AttributeType.Simple)
                    {
                        Column c = new Column(ad.name, ad.DataType, ad.Length, ad.AllowNull, ad.Description);
                        t4.AddColumn(c);
                    }
                    if (ad.type == AttributeType.Key)
                    {
                        hasPrimaryKey = true;
                        Column c = new Column(ad.name, ad.DataType, ad.Length, ad.AllowNull, true, false, ad.Description);
                        t4.AddPrimaryKey(c);
                    }
                    if (ad.type == AttributeType.MultiValued)
                        mulAttribute = ad;
                }
            }

            if (hasPrimaryKey)
            {
                t4.AddColumnFK(pk1);
                t4.AddColumnFK(pk2);
                t4.AddColumnFK(pk3);
            }
            else
            {
                t4.AddPrimaryKeyForeignKey(pk1);
                t4.AddPrimaryKeyForeignKey(pk2);
                if (f)
                    t4.AddPrimaryKeyForeignKey(pk3);
                else
                    t4.AddColumnFK(pk3);
            }

            mdp.AddTable(t4);
            mdp.AddForeignKey(nameRelationship + "1", t1, pk1, t4, pk1);
            mdp.AddForeignKey(nameRelationship + "2", t2, pk2, t4, pk2);
            mdp.AddForeignKey(nameRelationship + "3", t3, pk3, t4, pk3);

            //Xử lý trường hợp Multivalue
            if (mulAttribute.name != String.Empty)
                EntityHasMultivalueAttribute(t4, mulAttribute);
        }