"create tables from xsd to sql server database c#" Code Answer's

You're definitely familiar with the best coding language SQL that developers use to develop their projects and they get all their queries like "create tables from xsd to sql server database c#" answered properly. Developers are finding an appropriate answer about create tables from xsd to sql server database c# related to the SQL coding language. By visiting this online portal developers get answers concerning SQL codes question like create tables from xsd to sql server database c#. Enter your desired code related query in the search bar and get every piece of information about SQL code related question on create tables from xsd to sql server database c#. 

create tables from xsd to sql server database c#

By Obedient OcelotObedient Ocelot on Feb 09, 2021
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using Rule=System.Data.Rule;

namespace XSD2SQL
{
public class XSD2SQL
{
    private readonly Server _server;
    private readonly SqlConnection _connection;
    private Database _db;
    private DataSet _source;
    private string _databaseName;

    public XSD2SQL(string connectionString, DataSet source)
    {
        _connection = new SqlConnection(connectionString);
        _server = new Server(new ServerConnection(_connection));
        _source = source;
    }

    public void CreateDatabase(string databaseName)
    {
        _databaseName = databaseName;
        _db = _server.Databases[databaseName];
        if (_db != null) _db.Drop();
        _db = new Database(_server, _databaseName);
        _db.Create();
    }

    public void PopulateDatabase()
    {
        CreateTables(_source.Tables);
        CreateRelationships();
    }

    private void CreateRelationships()
    {
        foreach (DataTable table in _source.Tables)
        {
            foreach (DataRelation rel in table.ChildRelations)
                CreateRelation(rel);
        }
    }

    private void CreateRelation(DataRelation relation)
    {
        Table primaryTable = _db.Tables[relation.ParentTable.TableName];
        Table childTable = _db.Tables[relation.ChildTable.TableName];

        ForeignKey fkey = new ForeignKey(childTable, relation.RelationName);
        fkey.ReferencedTable = primaryTable.Name;

        fkey.DeleteAction = SQLActionTypeToSMO(relation.ChildKeyConstraint.DeleteRule);
        fkey.UpdateAction = SQLActionTypeToSMO(relation.ChildKeyConstraint.UpdateRule);


        for (int i = 0; i < relation.ChildColumns.Length; i++)
        {
            DataColumn col = relation.ChildColumns[i];
            ForeignKeyColumn fkc = new ForeignKeyColumn(fkey, col.ColumnName, relation.ParentColumns[i].ColumnName);

            fkey.Columns.Add(fkc);
        }

        fkey.Create();

    }

    private void CreateTables(DataTableCollection tables)
    {
        foreach (DataTable table in tables)
        {                
            DropExistingTable(table.TableName);
            Table newTable = new Table(_db, table.TableName);

            PopulateTable(ref newTable, table);                
            SetPrimaryKeys(ref newTable, table);
            newTable.Create();

        }
    }

    private void PopulateTable(ref Table outputTable, DataTable inputTable)
    {
        foreach (DataColumn column in inputTable.Columns)
        {
            CreateColumns(ref outputTable, column, inputTable);
        }
    }

    private void CreateColumns(ref Table outputTable, DataColumn inputColumn, DataTable inputTable)
    {
        Column newColumn = new Column(outputTable, inputColumn.ColumnName);
        newColumn.DataType = CLRTypeToSQLType(inputColumn.DataType);
        newColumn.Identity = inputColumn.AutoIncrement;
        newColumn.IdentityIncrement = inputColumn.AutoIncrementStep;
        newColumn.IdentitySeed = inputColumn.AutoIncrementSeed;
        newColumn.Nullable = inputColumn.AllowDBNull;
        newColumn.UserData = inputColumn.DefaultValue;

        outputTable.Columns.Add(newColumn);
    }

    private void SetPrimaryKeys(ref Table outputTable, DataTable inputTable)
    {
        Index newIndex = new Index(outputTable, "PK_" + outputTable.Name);
        newIndex.IndexKeyType = IndexKeyType.DriPrimaryKey;
        newIndex.IsClustered = false;

        foreach (DataColumn keyColumn in inputTable.PrimaryKey)
        {                                
            newIndex.IndexedColumns.Add(new IndexedColumn(newIndex, keyColumn.ColumnName, true));                
        }
        if (newIndex.IndexedColumns.Count > 0)
            outputTable.Indexes.Add(newIndex);
    }



    private DataType CLRTypeToSQLType(Type type)
    {
        switch (type.Name)
        {
            case "String":
                return DataType.NVarCharMax;

            case "Int32":
                return DataType.Int;

            case "Boolean":
                return DataType.Bit;

            case "DateTime":
                return DataType.DateTime;

            case "Byte[]":
                return DataType.VarBinaryMax;


        }

        return DataType.NVarCharMax;
    }

    private ForeignKeyAction SQLActionTypeToSMO(Rule rule)
    {
        string ruleStr = rule.ToString();

        return (ForeignKeyAction)Enum.Parse(typeof (ForeignKeyAction), ruleStr);
    }

    private void DropExistingTable(string tableName)
    {
        Table table = _db.Tables[tableName];
        if (table != null) table.Drop();
    }

}
}

Source: stackoverflow.com

Add Comment

0

All those coders who are working on the SQL based application and are stuck on create tables from xsd to sql server database c# can get a collection of related answers to their query. Programmers need to enter their query on create tables from xsd to sql server database c# related to SQL code and they'll get their ambiguities clear immediately. On our webpage, there are tutorials about create tables from xsd to sql server database c# for the programmers working on SQL code while coding their module. Coders are also allowed to rectify already present answers of create tables from xsd to sql server database c# while working on the SQL language code. Developers can add up suggestions if they deem fit any other answer relating to "create tables from xsd to sql server database c#". Visit this developer's friendly online web community, CodeProZone, and get your queries like create tables from xsd to sql server database c# resolved professionally and stay updated to the latest SQL updates. 

SQL answers related to "create tables from xsd to sql server database c#"

View All SQL queries

SQL queries related to "create tables from xsd to sql server database c#"

create tables from xsd to sql server database c# get tables in database sql drop all tables in azure sql database Database owner can't create new tables postgres checking tables without schema in sql server postgres duplicate database in same server while other session is using source database sql transact create cursor with dynamic tables sql select data from one database and insert into a different database delete all tables from database mysql show database not empty tables postgres get database list in sql server sql server restore database could not find driver (SQL: select * from information_schema.tables where table_schema = pics and table_name = migrations and table_type = 'BASE TABLE') sql show tables how to check tables without schema in sql oracle sql union tables with different columns sql get list of domains and the tables that use them sql select column name like from multiple tables how to make sure two tables have same exact data in sql oracle sql select from multiple tables get all tables with column name sql sql combine results from two tables how to get the elements that missing in other tables sql Sql drop all tables sql alter column name sql server https://www.jitendrazaa.com/blog/sql/sqlserver/export-documents-saved-as-blob-binary-from-sql-server/ create function sql server illuminate database queryexception could not find driver (sql select * from automatically update database last seen datetime in sql General error: 11 database disk image is malformed (SQL: select * from sqlite_master where type = 'table' and name = migrations) add primary key to database sql compress sql file database ubuntu ms sql database data size movie database sql queries how to store and retrieve image from sql database using c# in mvc create and attach user to a postgresql database how to create script to connect to oracle database and run query create sqlite database in laravel set utf8mb4 mysql tables show size of all tables postgres select tables with name like mysql find a column in all tables postgres mysql dump specific tables list mysql tables and views C# mysql data reader from two tables drop all tables db2 update all linkedserver tables with openquery on db dump multiple tables mysql Update All tables COLLATE DATABASE_DEFAULT oracle list partitioned tables how to check tables in mysql how to format tables in sqlplus stored procedure to change name of column for all dependent tables and views enlever les doubles espaces dans les tables postgresql select from 3 tables one is empty mysql drop tables Postgres show tables sql server get users sql server cast date dd/mm/yyyy sql server update c# example code get column name sql server declare table variable sql server rename table sql server sql server add unique constraint get current month last date in sql server sql server alter column base64 encode sql server sql server drop table if exists sql server to_date sql server to date sql server beginning of month copy table sql server sql server 2016 split string sql server concat string and int how to use group_concat in sql server id increment ms sql server with in sql server download sql server for mac remove default constraint sql server sql server pivot rows to columns how to connect to xampp sql server on windows cmd sql server today minus n buscar nombre de columna en todas las tablas sql server how to set foreign key in sql server sql server time stamp microsoft sql server year sql server function alter column sql server sql server select rows by distinct column How to Add a Default Value to a Column in MS SQL Server apt install sql server sql server version control is not in sql server load utilities in sql server sql server roles and users modificar tipo de dato sql server entity framework connection string sql server Join In Sql Server how to set all the min and sec data to zero in sql server blazor webassembly with direct sql server connection sql server management studio reset cache SQL SERVER 2016 cte correlated subqueries in microsoft sql server sql server split string and insert into table select sql server convert to guid insert into select * sql server how to send a query result as an email body sql server serilog-in-aspnetcore-3 sql server configuration sql server phone constraint SQL SERVER 2016 TRIM install sql server management studio ubuntu sql server remove 0 from left how to get the date diff of 2 dates in the same fieldin sql server open xml file sql server sql server system messeges sql server udf performance sql server delete records with specific date delete row in sql server join sql server add time to date SQL Server equivalent of MySQL's NOW() script out foreign keys sql server sql server whoami local sql server r dbConnect(odbc::odbc() to ms sql server remote databricks install odbc driver connect to sql server convert multiple columns to ROws in sql server transaction and commit trong sql server executescalar in sql server sql server manager close connection sql server update column based on another table concat two columns in sql server sql server provider name connection string group_concat sql server isnull sql server SQL server datetime compare sql server express download where query in sql server sql server port number sql server group by concatenate how to update sql server version SQL SERVER microsoft How to Add Column at Specific Location in Table bit in sql server c# how to display enum value sql server change date in pivot table to month in sql server multiple tricky query in sql server sql server isnull function nor working count how to combine rows in sql server procedure Sql server Cost Fifo query how much space does sql server take per row httpwebclient request and insert to sql server rename column name sql server java.sql.SQLException: Unknown initial character set index '255' received from server. Initial client character set can be forced via the 'characterEncoding' property. Trigger Sql server Alter table modify column sql server How to reset identity column in sql server convert datetime to date in sql server convert date to string sql server oracle sql create user create table if not exists sql how to create table in sql sql syntax create timestamp column create user defined table type in sql create new databse sql how to create an SQL save method in ruby Google BigQuery how to create machine learning model using SQL pl sql create table from another table sql create table with columns as another table pl sql create table identity column how to create a delete stored procedure in sql create query as sql access vba Apache Derby: Create SQL Dump with data database setup in django set username and password for postgresql database Illuminate\Database\QueryException : SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost' database url postgres set database timezone mysql mysql backup database mysql backup database command line how to import mysql database command line which takes more space in a database a datetime or separate date and time columns? database interface how to rename a database in tsql how to add database to portfolio Manage Database in MySQL database traccar "/** MySQL database password */" ext:txt | ext:cfg | ext:env | ext:ini scheduled mysql database backup in linux SQLSTATE[HY000] [2002] Permission denied when connect to digitalocean cloud database what to test in database how to backup postgresql database using pg_dump transaction database with php update database collation in postgresql transaction database php audit user login history in database mysql how to change the database in sqlplus difference berween database and data base management system no database schema database returning string value for integer columns

Browse Other Code Languages

CodeProZone