I wrote a method which copies a table from SQL Server to a .NET-DataTable:
public static DataTable SQLtoDataTable(string _connectionString, string _tableName)
{
DataTable dt = new DataTable();
string queryString = "SELECT * FROM " + _tableName;
using (SqlConnection connection = new SqlConnection(_connectionString))
{
using (SqlCommand queryCMD = new SqlCommand(queryString))
{
using (SqlDataAdapter da = new SqlDataAdapter(queryCMD))
{
queryCMD.Connection = connection;
connection.Open();
da.Fill(dt);
connection.Close();
}
}
}
return dt;
}
Unfortunately this method does not seem to work 100% correctly. While columns and row data are transferred 1:1, it seems like the AllowDBNULL value is set to true for every single column no matter if it is set to true or false in the database. Do I miss something or is there a better way to insert this kind of information into a DataTable?
DataTableis "as rarely as possible, when all other possible models have been eliminated"... is there any reason you can't represent this in a proper object model?class Customer {...}andclass Order {...}.DataTableis not the way to go for data access / storage, IMO.public static List<T> ReadTable<T>(...). Table name could be passed in as a string, or could just use thetypeof(T).Name, ortypeof(T).GetCustomAttribute<TableName>().Name. Plenty of options there. The only time you need to useDataTable(or a similar approach) is when writing a tool like SSMS, in which the structure cannot be known in advance.