Search code examples
c#sqlsql-serverclassgenerate

how to generate c# class from sql multiple tables (related tables with foreign keys)


I would like to generate C# class from sql queries. I can do it just for a table, but i have a header table and more than one detail tables. I' d like to generate classes for all of them and they are related with pk and fk's.


Solution

  • I can't comment, hence the answer.

    This answer isn't perfect because it's for oracle. I use bellow code to run a query and get access to the results. You can easily generate classes from this.

            DataTable dataTable = new DataTable();
            using (OracleConnection oracleConnection = new OracleConnection(constr))
            {
                oracleConnection.Open();
                OracleCommand oracleCommand = new OracleCommand(query, oracleConnection);
                OracleDataAdapter da = new OracleDataAdapter(oracleCommand);
    
                //TODO: This seems to get all the data. We just want 1 row or no rows and only column info..
                da.Fill(dataTable);
    
                oracleConnection.Close();//Close just in case
            }
    
            foreach (DataColumn column in dataTable.Columns)
            {
                //Use these properties to generate a class
                column.ColumnName;
                column.DataType;
                column.AllowDBNull; 
                column.DefaultValue;
            }