xxxxxxxxxx
using System;
using System.Data;
using System.Data.SqlClient;
public class SqlToCSharpConverter
{
public static string ConvertSqlTableToCSharpClass(string tableName)
{
// The SQL connection string
string connectionString = "Your_Connection_String";
// Create the SQL connection
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Open the connection
connection.Open();
// Retrieve the table schema
DataTable schemaTable = connection.GetSchema("Columns", new[] { null, null, tableName });
// Create the class definition
string classDefinition = $"public class {tableName}" + Environment.NewLine;
classDefinition += "{" + Environment.NewLine;
// Retrieve column names and types
foreach (DataRow row in schemaTable.Rows)
{
string columnName = row["COLUMN_NAME"].ToString();
string dataType = row["DATA_TYPE"].ToString();
// Map SQL data types to C# data types
string csharpDataType = MapSqlDataTypeToCSharp(dataType);
// Append field declarations
classDefinition += $"\tpublic {csharpDataType} {columnName} {{ get; set; }}" + Environment.NewLine;
}
classDefinition += "}";
return classDefinition;
}
}
private static string MapSqlDataTypeToCSharp(string dataType)
{
// Modify the type mappings as per your requirements
switch (dataType.ToLower())
{
case "bigint":
return "long";
case "binary":
case "image":
case "timestamp":
case "varbinary":
return "byte[]";
case "bit":
return "bool";
case "char":
case "nchar":
case "ntext":
case "nvarchar":
case "sysname":
case "text":
case "varchar":
return "string";
case "date":
case "datetime":
case "datetime2":
case "smalldatetime":
return "DateTime";
case "datetimeoffset":
return "DateTimeOffset";
case "decimal":
case "money":
case "numeric":
case "smallmoney":
return "decimal";
case "float":
return "double";
case "int":
return "int";
case "real":
return "float";
case "smallint":
return "short";
case "time":
return "TimeSpan";
case "tinyint":
return "byte";
case "uniqueidentifier":
return "Guid";
default:
return "object";
}
}
}
xxxxxxxxxx
to convert sql table to c# class
there are mulitple ways to do it here is two ways
1. you can use the Scaffold-DbContext (Entity Framework Core)
Scaffold-DbContext "Your-Connection-String" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
by providing you connection string here you can generate the classes from the db you want
2. you can use any online converter where you provide the create table script and the online tool will convert it to C# class
eg:- https://codverter.com/src/sqltoclass