Ejemplo n.º 1
0
        public void CheckCreateTableCommand()
        {
            // Arrange
            var schema = new SqlTableSchema("TestUpsert", new List<Column>
                                                          {
                                                              new NumericColumn
                                                              {
                                                                  Name = "first",
                                                                  DataType = "int",
                                                                  OrdinalPosition = 1,
                                                                  Nullable = false,
                                                              },
                                                              new TextColumn
                                                              {
                                                                  Name = "second",
                                                                  DataType = "ntext",
                                                                  OrdinalPosition = 2,
                                                                  Nullable = true,
                                                              },
                                                              new DateColumn
                                                              {
                                                                  Name = "third",
                                                                  DataType = "datetime2",
                                                                  OrdinalPosition = 3,
                                                                  Precision = 4,
                                                              }
                                                          });

            // Act
            var cmdText = schema.ToCreateTableCommandText();

            // Assert
            Assert.AreEqual("CREATE TABLE TestUpsert ([first] int NOT NULL, [second] ntext NULL, [third] datetime2(4) NOT NULL)", cmdText);
        }
Ejemplo n.º 2
0
        public void CheckCreateTableCommand()
        {
            // Arrange
            var schema = new SqlTableSchema("TestUpsert", new List <Column>
            {
                new NumericColumn
                {
                    Name            = "first",
                    DataType        = "int",
                    OrdinalPosition = 1,
                    Nullable        = false,
                },
                new TextColumn
                {
                    Name            = "second",
                    DataType        = "ntext",
                    OrdinalPosition = 2,
                    Nullable        = true,
                },
                new DateColumn
                {
                    Name            = "third",
                    DataType        = "datetime2",
                    OrdinalPosition = 3,
                    Precision       = 4,
                }
            });

            // Act
            var cmdText = schema.ToCreateTableCommandText();

            // Assert
            Assert.AreEqual("CREATE TABLE TestUpsert ([first] int NOT NULL, [second] ntext NULL, [third] datetime2(4) NOT NULL)", cmdText);
        }
Ejemplo n.º 3
0
        public void EndToEndInsert()
        {
            // Arrange
            using (var connection = DatabaseHelper.CreateAndOpenConnection())
            {
                var targetSchema = SqlTableSchema.LoadFromDatabase(connection, "TestUpsert", "ident");

                var upserter = new DataTableUpserter(targetSchema);
                upserter.RetrieveIdentity = true;

                var dataTable = new DataTable("TestUpsert");
                dataTable.Columns.Add("ident");
                dataTable.Columns.Add("key_part_1");
                dataTable.Columns.Add("key_part_2");
                dataTable.Columns.Add("nullable_text");
                dataTable.Columns.Add("nullable_number");

                for (int i = 1; i <= 10; i++)
                {
                    dataTable.Rows.Add(DBNull.Value, "TEST", i, String.Format("some text here {0}", i), i * 11);
                }

                // Act
                IEnumerable <int> result = upserter.Upsert(connection, dataTable);
                var idents = new List <int>(result);

                // Assert
                Assert.AreEqual(10, idents.Count);

                foreach (DataRow row in dataTable.Rows)
                {
                    Assert.AreEqual(row["key_part_2"], row["ident"]);
                }
            }
        }
        private void FindTableNames(DbConnection connection, DatabaseSchema dbSchema)
        {
            using (var cmd = connection.CreateCommand())
            {
                cmd.CommandText = SelectColumns;
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var schemaAndTableName = GetTableNameFromReader(reader);

                        var tableSchema = dbSchema.GetTable(schemaAndTableName.Schema, schemaAndTableName.TableName);

                        if (tableSchema == null)
                        {
                            tableSchema = new SqlTableSchema(schemaAndTableName.Schema, schemaAndTableName.TableName,
                                                             GetSelectAllQueryForTable(schemaAndTableName.Schema, schemaAndTableName.TableName));
                            dbSchema.Tables.Add(tableSchema);
                        }

                        var columnName = reader["COLUMN_NAME"].ToString();
                        var columnType = MapColumnType(reader["DATA_TYPE"].ToString());

                        tableSchema.Columns.Add(new TableColumn(columnType, columnName));
                    }
                }
            }
        }
Ejemplo n.º 5
0
        public void CheckDropTableCommand()
        {
            // Arrange
            var schema = new SqlTableSchema("TestUpsert");

            // Act
            var cmdText = schema.ToDropTableCommandText();

            // Assert
            Assert.AreEqual("DROP TABLE TestUpsert", cmdText);
        }
Ejemplo n.º 6
0
        public void CheckDropTableCommand()
        {
            // Arrange
            var schema = new SqlTableSchema("TestUpsert");

            // Act
            var cmdText = schema.ToDropTableCommandText();

            // Assert
            Assert.AreEqual("DROP TABLE TestUpsert", cmdText);
        }
Ejemplo n.º 7
0
        public void RetrieveTableSchemaNotExist()
        {
            using (var connection = DatabaseHelper.CreateAndOpenConnection())
            {
                // Arrange

                // Act
                SqlTableSchema.LoadFromDatabase(connection, "DoesNotExist", null);

                // Assert
            }
        }
Ejemplo n.º 8
0
        public void EndToEnd()
        {
            using (var connection = DatabaseHelper.CreateAndOpenConnection())
            {
                // Arrange
                var targetSchema = SqlTableSchema.LoadFromDatabase(connection, "TestUpsert", "ident");

                var columnMappings = new Dictionary <string, Func <TestDto, object> >
                {
                    { "ident", d => d.Ident },
                    { "key_part_1", d => d.KeyPart1 },
                    { "key_part_2", d => d.KeyPart2 },
                    { "nullable_text", d => d.Text },
                    { "nullable_number", d => d.Number },
                    { "nullable_datetimeoffset", d => d.Date },
                };

                Action <TestDto, int> identUpdater = (d, i) => d.Ident = i;

                var upserter = new TypedUpserter <TestDto>(targetSchema, columnMappings, identUpdater);

                var items = new List <TestDto>();

                for (int i = 1; i <= 10; i++)
                {
                    items.Add(
                        new TestDto
                    {
                        Ident    = null,
                        KeyPart1 = "TEST",
                        KeyPart2 = (short)i,
                        Text     = String.Format("some text here {0}", i),
                        Number   = i,
                        Date     = new DateTimeOffset(new DateTime(2010, 11, 14, 12, 0, 0), TimeSpan.FromHours(i))
                    });
                }

                // Act
                upserter.Upsert(connection, items);

                // Assert
                foreach (var testDto in items)
                {
                    Assert.AreEqual(testDto.Number, testDto.Ident);
                }
            }
        }
Ejemplo n.º 9
0
        public void EndToEndInsertUpdate()
        {
            // Arrange
            using (var connection = DatabaseHelper.CreateAndOpenConnection())
            {
                connection.ExecuteCommands(Resources.PopulateTable);

                var targetSchema = SqlTableSchema.LoadFromDatabase(connection, "TestUpsert", "ident");

                var upserter = new DataTableUpserter(targetSchema);
                upserter.RetrieveIdentity = true;

                var dataTable = new DataTable("TestUpsert");
                dataTable.Columns.Add("ident");
                dataTable.Columns.Add("key_part_1");
                dataTable.Columns.Add("key_part_2");
                dataTable.Columns.Add("nullable_text");
                dataTable.Columns.Add("nullable_number");

                for (int i = 1; i <= 10; i++)
                {
                    dataTable.Rows.Add(i, "TEST", i, String.Format("some text here {0}", i), i);
                    dataTable.Rows.Add(DBNull.Value, "BLAH", i, String.Format("some text here {0}", i), i + 10);
                }

                // Act
                IEnumerable <int> result = upserter.Upsert(connection, dataTable);
                var idents = new List <int>(result);

                // Assert
                Assert.AreEqual(10, idents.Count);

                foreach (DataRow row in dataTable.Rows)
                {
                    Assert.AreEqual(row["nullable_number"], row["ident"]);
                }

                Assert.AreEqual(20, connection.ExecuteScalar("SELECT COUNT(1) FROM [TestUpsert]"));
                Assert.AreEqual(10, connection.ExecuteScalar("SELECT COUNT(1) FROM [TestUpsert] WHERE [key_part_1] != 'BLAH'"));
                Assert.AreEqual(10, connection.ExecuteScalar("SELECT COUNT(1) FROM [TestUpsert] WHERE [key_part_1] = 'BLAH'"));
            }
        }
Ejemplo n.º 10
0
        protected override string GetQueryByPrimaryKey(RootCollection collection, SqlTableSchema tableSchema, string[] primaryKeyValues, out Dictionary <string, object> queryParameters)
        {
            var primaryKeyColumns = tableSchema.PrimaryKeyColumns;

            if (primaryKeyColumns.Count != primaryKeyValues.Length)
            {
                queryParameters = null;
                throw new InvalidOperationException("Invalid parameters count. Primary key has " + primaryKeyColumns.Count + " columns, but " + primaryKeyValues.Length + " values were provided.");
            }

            var    parameters = new Dictionary <string, object>();
            string query      = $"select * from \"{QuoteTable(collection.SourceTableSchema, collection.SourceTableName)}\" where "
                                + string.Join(" and ", primaryKeyColumns.Select((column, idx) =>
            {
                parameters["p" + idx] = ValueAsObject(tableSchema, column, primaryKeyValues, idx);
                return($"\"{QuoteColumn(column)}\" = :p{idx}");
            }));


            queryParameters = parameters;
            return(query);
        }
Ejemplo n.º 11
0
        private TableSchema GetTable(string tableName, SqlConnection conn, OleDbConnection pkConn,
                                     Dictionary <string, ForeignKeyInfo> fkOneTable)
        {
            string[] restrictions = new string[4];

            restrictions[1] = "dbo";
            restrictions[2] = tableName;

            DataTable tt = conn.GetSchema("Tables", restrictions);

            if (tt.Rows.Count == 0)
            {
                return(null);
            }
            TableSchema tableSchema = new SqlTableSchema();

            tableSchema.Name   = tt.Rows[0]["TABLE_NAME"].ToString();
            tableSchema.IsView = tt.Rows[0]["TABLE_TYPE"].ToString().Equals("VIEW", StringComparison.OrdinalIgnoreCase);
            restrictions       = new string[4];
            restrictions[1]    = "dbo";
            restrictions[2]    = tableSchema.Name;

            DataTable ff = conn.GetSchema("Columns", restrictions);

            restrictions[2] = tableSchema.Name;
            if (pkConn.State == ConnectionState.Closed)
            {
                pkConn.Open();
            }
            List <string> pkColumns = new List <string>();

            string[]  parameters = new string[] { conn.Database, "dbo", tableSchema.Name };
            DataTable pkTable    = pkConn.GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, parameters);

            pkConn.Close();

            foreach (DataRow indexRow in pkTable.Rows)
            {
                pkColumns.Add(indexRow["column_name"].ToString());
            }
            string  sql = string.Format(@"
select COLUMNPROPERTY(a.id, a.name, 'IsIdentity') as IsIdentity,
       a.name
       ,g.value
  from syscolumns a
 inner join systypes b on a.xtype = b.xusertype
 inner join sysobjects d on a.id = d.id
                        and d.xtype = 'U'
 left join sys.extended_properties g on d.id = g.major_id and a.colid = g.minor_id
 where d.name = '{0}'", tableName);
            DataSet ds  = SqlHelper.ExecuteDataset(conn, CommandType.Text, sql);
            Dictionary <string, bool>   dict_IsIdentity  = new Dictionary <string, bool>();
            Dictionary <string, string> dict_Description = new Dictionary <string, string>();

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                dict_IsIdentity.Add((string)row["name"], row["IsIdentity"].Equals(1)?true:false);
                if (row["Value"] != DBNull.Value)
                {
                    dict_Description.Add((string)row["name"], (string)row["Value"]);
                }
            }

            foreach (DataRow fRow in ff.Rows)
            {
                string name        = fRow["COLUMN_NAME"].ToString();
                bool   allowDBNull = fRow["IS_NULLABLE"].ToString().Equals("NO") ? false : true;
                string dataType    = fRow["DATA_TYPE"].ToString();
                string nativeType  = fRow["DATA_TYPE"].ToString();
                byte   precision   = 0;
                byte.TryParse(fRow["NUMERIC_PRECISION"].ToString(), out precision);

                int scale = 0;
                int.TryParse(fRow["NUMERIC_SCALE"].ToString(), out scale);

                int size = 0;
                int.TryParse(fRow["CHARACTER_MAXIMUM_LENGTH"].ToString(), out size);
                if (size == 0)
                {
                    int.TryParse(fRow["CHARACTER_OCTET_LENGTH"].ToString(), out size);
                }

                SqlColumnSchema columnSchema = new SqlColumnSchema(
                    pkColumns.Contains(name), name, dataType, nativeType, size, precision, scale, allowDBNull);
                tableSchema.Columns.Add(columnSchema);

                columnSchema.IsIdent     = dict_IsIdentity.ContainsKey(name)?dict_IsIdentity[name]:false;
                columnSchema.Description = dict_Description.ContainsKey(name) ? dict_Description[name] : "";

                if (fkOneTable != null)
                {
                    if (fkOneTable.ContainsKey(columnSchema.Name))
                    {
                        ForeignKeyInfo fkInfo = fkOneTable[columnSchema.Name];
                        columnSchema.ForeignKeyTable  = fkInfo.FK_Table;
                        columnSchema.ForeignKeyColumn = fkInfo.FK_Column;
                    }
                }
            }
            //获得外键
            //DataTable fk = conn.GetSchema("ForeignKeys", restrictions);
            //foreach (DataRow fkRow in fk.Rows)
            //{
            //    fk.WriteXml("1.xml");
            //}
            return(tableSchema);
        }
Ejemplo n.º 12
0
        public void PopulateFromReader()
        {
            // Arrange
            var columnDetail = new DataTable();

            columnDetail.Columns.AddRange(new List <DataColumn>
            {
                new DataColumn
                {
                    ColumnName = "COLUMN_NAME",
                    DataType   = typeof(string),
                },
                new DataColumn
                {
                    ColumnName = "ORDINAL_POSITION",
                    DataType   = typeof(int),
                },
                new DataColumn
                {
                    ColumnName = "IS_NULLABLE",
                    DataType   = typeof(string),
                },
                new DataColumn
                {
                    ColumnName = "DATA_TYPE",
                    DataType   = typeof(string),
                },
                new DataColumn
                {
                    ColumnName  = "CHARACTER_MAXIMUM_LENGTH",
                    DataType    = typeof(int),
                    AllowDBNull = true,
                },
                new DataColumn
                {
                    ColumnName  = "CHARACTER_OCTET_LENGTH",
                    DataType    = typeof(int),
                    AllowDBNull = true,
                },
                new DataColumn
                {
                    ColumnName  = "NUMERIC_PRECISION",
                    DataType    = typeof(byte),
                    AllowDBNull = true,
                },
                new DataColumn
                {
                    ColumnName  = "NUMERIC_PRECISION_RADIX",
                    DataType    = typeof(short),
                    AllowDBNull = true,
                },
                new DataColumn
                {
                    ColumnName  = "NUMERIC_SCALE",
                    DataType    = typeof(int),
                    AllowDBNull = true,
                },
                new DataColumn
                {
                    ColumnName  = "DATETIME_PRECISION",
                    DataType    = typeof(short),
                    AllowDBNull = true,
                },
            }.ToArray());

            columnDetail.Rows.Add("ident", 1, "NO", "int", DBNull.Value, DBNull.Value, (byte)10, (short)10, 0, DBNull.Value);
            columnDetail.Rows.Add("key_part_1", 2, "NO", "nchar", 4, 8, DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value);
            columnDetail.Rows.Add("key_part_2", 3, "NO", "smallint", DBNull.Value, DBNull.Value, (byte)5, (short)10, 0, DBNull.Value);
            columnDetail.Rows.Add("nullable_text", 4, "YES", "nvarchar", 50, 100, DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value);
            columnDetail.Rows.Add("nullable_number", 5, "YES", "int", DBNull.Value, DBNull.Value, (byte)10, (short)10, 0, DBNull.Value);
            columnDetail.Rows.Add("nullable_datetimeoffset", 6, "YES", "datetimeoffset", DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value, (short)7);
            columnDetail.Rows.Add("nullable_money", 7, "YES", "money", DBNull.Value, DBNull.Value, (byte)19, (short)10, 4, DBNull.Value);
            columnDetail.Rows.Add("nullable_varbinary", 8, "YES", "varbinary", -1, -1, DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value);
            columnDetail.Rows.Add("nullable_image", 9, "YES", "image", 2147483647, 2147483647, DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value);
            columnDetail.Rows.Add("nullable_xml", 10, "YES", "xml", -1, -1, DBNull.Value, DBNull.Value, DBNull.Value, DBNull.Value);

            var keyDetail = new DataTable();

            keyDetail.Columns.AddRange(new List <DataColumn>
            {
                new DataColumn
                {
                    ColumnName = "COLUMN_NAME",
                    DataType   = typeof(string),
                },
            }.ToArray());

            keyDetail.Rows.Add("key_part_1");
            keyDetail.Rows.Add("key_part_2");

            var dataTableReader = new DataTableReader(new[] { columnDetail, keyDetail });

            #region Columns
            var expectedColumns = new List <Column>
            {
                new NumericColumn
                {
                    Name            = "ident",
                    OrdinalPosition = 1,
                    Nullable        = false,
                    DataType        = "int",
                    Precision       = 10,
                    Radix           = 10,
                    Scale           = 0,
                },
                new TextColumn
                {
                    Name            = "key_part_1",
                    OrdinalPosition = 2,
                    Nullable        = false,
                    DataType        = "nchar",
                    CharLength      = 4,
                    ByteLength      = 8,
                },
                new NumericColumn
                {
                    Name            = "key_part_2",
                    OrdinalPosition = 3,
                    Nullable        = false,
                    DataType        = "smallint",
                    Precision       = 5,
                    Radix           = 10,
                    Scale           = 0,
                },
                new TextColumn
                {
                    Name            = "nullable_text",
                    OrdinalPosition = 4,
                    Nullable        = true,
                    DataType        = "nvarchar",
                    CharLength      = 50,
                    ByteLength      = 100,
                },
                new NumericColumn
                {
                    Name            = "nullable_number",
                    OrdinalPosition = 5,
                    Nullable        = true,
                    DataType        = "int",
                    Precision       = 10,
                    Radix           = 10,
                    Scale           = 0,
                },
                new DateColumn
                {
                    Name            = "nullable_datetimeoffset",
                    OrdinalPosition = 6,
                    Nullable        = true,
                    DataType        = "datetimeoffset",
                    Precision       = 7,
                },
                new NumericColumn
                {
                    Name            = "nullable_money",
                    OrdinalPosition = 7,
                    Nullable        = true,
                    DataType        = "money",
                    Precision       = 19,
                    Radix           = 10,
                    Scale           = 4,
                },
                new TextColumn
                {
                    Name            = "nullable_varbinary",
                    OrdinalPosition = 8,
                    Nullable        = true,
                    DataType        = "varbinary",
                    CharLength      = -1,
                    ByteLength      = -1,
                },
                new TextColumn
                {
                    Name            = "nullable_image",
                    OrdinalPosition = 9,
                    Nullable        = true,
                    DataType        = "image",
                    CharLength      = 2147483647,
                    ByteLength      = 2147483647,
                },
                new Column
                {
                    Name            = "nullable_xml",
                    OrdinalPosition = 10,
                    Nullable        = true,
                    DataType        = "xml",
                },
            };

            var expectedKeyColumns = new List <Column>
            {
                new TextColumn
                {
                    Name            = "key_part_1",
                    OrdinalPosition = 2,
                    Nullable        = false,
                    DataType        = "nchar",
                    CharLength      = 4,
                    ByteLength      = 8,
                },
                new NumericColumn
                {
                    Name            = "key_part_2",
                    OrdinalPosition = 3,
                    Nullable        = false,
                    DataType        = "smallint",
                    Precision       = 5,
                    Radix           = 10,
                    Scale           = 0,
                },
            };
            #endregion

            // Act
            var schema = SqlTableSchema.LoadFromReader("TestUpsert", dataTableReader, "ident");

            // Assert
            Assert.AreEqual("TestUpsert", schema.TableName);
            CollectionAssert.AreEqual(expectedColumns, schema.Columns, new ColumnComparer());
            CollectionAssert.AreEqual(expectedKeyColumns, schema.PrimaryKeyColumns, new ColumnComparer());
        }
Ejemplo n.º 13
0
        public void RetrieveTableSchema()
        {
            using (var connection = DatabaseHelper.CreateAndOpenConnection())
            {
                // Arrange
                #region Columns
                var expectedColumns = new List <Column>
                {
                    new NumericColumn
                    {
                        Name            = "ident",
                        OrdinalPosition = 1,
                        Nullable        = false,
                        DataType        = "int",
                        Precision       = 10,
                        Radix           = 10,
                        Scale           = 0,
                    },
                    new TextColumn
                    {
                        Name            = "key_part_1",
                        OrdinalPosition = 2,
                        Nullable        = false,
                        DataType        = "nchar",
                        CharLength      = 4,
                        ByteLength      = 8,
                    },
                    new NumericColumn
                    {
                        Name            = "key_part_2",
                        OrdinalPosition = 3,
                        Nullable        = false,
                        DataType        = "smallint",
                        Precision       = 5,
                        Radix           = 10,
                        Scale           = 0,
                    },
                    new TextColumn
                    {
                        Name            = "nullable_text",
                        OrdinalPosition = 4,
                        Nullable        = true,
                        DataType        = "nvarchar",
                        CharLength      = 50,
                        ByteLength      = 100,
                    },
                    new NumericColumn
                    {
                        Name            = "nullable_number",
                        OrdinalPosition = 5,
                        Nullable        = true,
                        DataType        = "int",
                        Precision       = 10,
                        Radix           = 10,
                        Scale           = 0,
                    },
                    new DateColumn
                    {
                        Name            = "nullable_datetimeoffset",
                        OrdinalPosition = 6,
                        Nullable        = true,
                        DataType        = "datetimeoffset",
                        Precision       = 7,
                    },
                    new NumericColumn
                    {
                        Name            = "nullable_money",
                        OrdinalPosition = 7,
                        Nullable        = true,
                        DataType        = "money",
                        Precision       = 19,
                        Radix           = 10,
                        Scale           = 4,
                    },
                    new TextColumn
                    {
                        Name            = "nullable_varbinary",
                        OrdinalPosition = 8,
                        Nullable        = true,
                        DataType        = "varbinary",
                        CharLength      = -1,
                        ByteLength      = -1,
                    },
                    new TextColumn
                    {
                        Name            = "nullable_image",
                        OrdinalPosition = 9,
                        Nullable        = true,
                        DataType        = "image",
                        CharLength      = 2147483647,
                        ByteLength      = 2147483647,
                    },
                    new Column
                    {
                        Name            = "nullable_xml",
                        OrdinalPosition = 10,
                        Nullable        = true,
                        DataType        = "xml",
                    },
                };

                var expectedKeyColumns = new List <Column>
                {
                    new TextColumn
                    {
                        Name            = "key_part_1",
                        OrdinalPosition = 2,
                        Nullable        = false,
                        DataType        = "nchar",
                        CharLength      = 4,
                        ByteLength      = 8,
                    },
                    new NumericColumn
                    {
                        Name            = "key_part_2",
                        OrdinalPosition = 3,
                        Nullable        = false,
                        DataType        = "smallint",
                        Precision       = 5,
                        Radix           = 10,
                        Scale           = 0,
                    },
                };
                #endregion

                // Act
                SqlTableSchema schema = SqlTableSchema.LoadFromDatabase(connection, "TestUpsert", "ident");

                // Assert
                Assert.AreEqual("TestUpsert", schema.TableName);
                CollectionAssert.AreEqual(expectedColumns, schema.Columns, new ColumnComparer());
                CollectionAssert.AreEqual(expectedKeyColumns, schema.PrimaryKeyColumns, new ColumnComparer());
            }
        }
Ejemplo n.º 14
0
 private static SqlEntityAdapter CreateAdapter(Type type)
 {
     return(new SqlEntityAdapter(CreateDatabase(), new SqlServerDialectProvider(SqlTableSchema.Load(type))));
 }
Ejemplo n.º 15
0
        private TableSchema GetTable(string tableName,SqlConnection conn, OleDbConnection pkConn ,
            Dictionary<string,ForeignKeyInfo> fkOneTable)
        {
            string[] restrictions = new string[4];

            restrictions[1] = "dbo";
            restrictions[2] = tableName;

            DataTable tt = conn.GetSchema("Tables", restrictions);
            if (tt.Rows.Count == 0)
                return null;
            TableSchema tableSchema = new SqlTableSchema();
            tableSchema.Name = tt.Rows[0]["TABLE_NAME"].ToString();
            tableSchema.IsView = tt.Rows[0]["TABLE_TYPE"].ToString().Equals("VIEW", StringComparison.OrdinalIgnoreCase);
            restrictions = new string[4];
            restrictions[1] = "dbo";
            restrictions[2] = tableSchema.Name;

            DataTable ff = conn.GetSchema("Columns", restrictions);
            restrictions[2] = tableSchema.Name;
            if (pkConn.State == ConnectionState.Closed)
            {
                pkConn.Open();
            }
            List<string> pkColumns = new List<string>();
            string[] parameters = new string[] { conn.Database, "dbo", tableSchema.Name };
            DataTable pkTable = pkConn.GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, parameters);
            pkConn.Close();

            foreach (DataRow indexRow in pkTable.Rows)
            {
                pkColumns.Add(indexRow["column_name"].ToString());
            }
            string sql = string.Format(@"
            select COLUMNPROPERTY(a.id, a.name, 'IsIdentity') as IsIdentity,
               a.name
               ,g.value
              from syscolumns a
             inner join systypes b on a.xtype = b.xusertype
             inner join sysobjects d on a.id = d.id
                        and d.xtype = 'U'
             left join sys.extended_properties g on d.id = g.major_id and a.colid = g.minor_id
             where d.name = '{0}'", tableName);
            DataSet ds = SqlHelper.ExecuteDataset(conn, CommandType.Text, sql);
            Dictionary<string, bool> dict_IsIdentity = new Dictionary<string, bool>();
            Dictionary<string,string> dict_Description = new Dictionary<string,string>();

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                dict_IsIdentity.Add((string)row["name"], row["IsIdentity"].Equals(1)?true:false);
                if (row["Value"] != DBNull.Value)
                {
                    dict_Description.Add((string)row["name"], (string)row["Value"]);
                }
            }

            foreach (DataRow fRow in ff.Rows)
            {
                string name = fRow["COLUMN_NAME"].ToString();
                bool allowDBNull = fRow["IS_NULLABLE"].ToString().Equals("NO") ? false : true;
                string dataType = fRow["DATA_TYPE"].ToString();
                string nativeType = fRow["DATA_TYPE"].ToString();
                byte precision = 0;
                byte.TryParse(fRow["NUMERIC_PRECISION"].ToString(), out precision);

                int scale = 0;
                int.TryParse(fRow["NUMERIC_SCALE"].ToString(), out scale);

                int size = 0;
                int.TryParse(fRow["CHARACTER_MAXIMUM_LENGTH"].ToString(), out size);
                if (size == 0)
                {
                    int.TryParse(fRow["CHARACTER_OCTET_LENGTH"].ToString(), out size);
                }

                SqlColumnSchema columnSchema = new SqlColumnSchema(
                    pkColumns.Contains(name), name, dataType, nativeType, size, precision, scale, allowDBNull);
                tableSchema.Columns.Add(columnSchema);

                columnSchema.IsIdent = dict_IsIdentity.ContainsKey(name)?dict_IsIdentity[name]:false;
                columnSchema.Description = dict_Description.ContainsKey(name) ? dict_Description[name] : "";

                if (fkOneTable != null)
                {
                    if (fkOneTable.ContainsKey(columnSchema.Name))
                    {
                        ForeignKeyInfo fkInfo = fkOneTable[columnSchema.Name];
                        columnSchema.ForeignKeyTable = fkInfo.FK_Table;
                        columnSchema.ForeignKeyColumn = fkInfo.FK_Column;
                    }
                }
            }
            //获得外键
            //DataTable fk = conn.GetSchema("ForeignKeys", restrictions);
            //foreach (DataRow fkRow in fk.Rows)
            //{
            //    fk.WriteXml("1.xml");
            //}
            return tableSchema;
        }
Ejemplo n.º 16
0
 public SqlEntityAdapter(Database db, Type entityType) : base(db, new SqlServerDialectProvider(SqlTableSchema.Load(entityType)))
 {
 }
Ejemplo n.º 17
0
 public static EntityAdapter CreateAdapter(Type entityType)
 {
     return(new EntityAdapter(CreateDb(), new SqlServerDialectProvider(SqlTableSchema.Load(entityType))));
 }