Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - How to tell if DataColumn supports nulls?

I have a datatable that comes from an SQL request. While I am really working against a table using OLEDB, even if I get the table from my SQL server, I have the same problem.

If I fill the datatable and then query the DataColumns - they all say AllowDBNull== true and allowNull == true. But if I look at the table in SSMS, it states otherwise.

string selectStmt= "Select  * from foobar; "
DataSet NewData = new DataSet();
using (SqlConnection DataConn = new SqlConnection(MyConnectionString))
{   
    SqlDataAdapter DataAdapter = new SqlDataAdapter(selectStmt, DataConn );
    var Results = DataAdapter.Fill(NewData, tableName);
}
DataColumn Col = NewData.Tables[0].Columns[0];
// Col.AllowDBNull is always true as is Col.AllowNull

I also can't seem to figure out where to get the length of a string field.

This makes it a little difficult to implement some simple client side error checking before I try to upload data.

If I were only dealing with SQL server based tables, I could use Microsoft.SqlServer.Management.Sdk and Microsoft.SqlServer.Management.Smo. Since I am not, that's out.

like image 671
JustMeToo Avatar asked Sep 29 '22 06:09

JustMeToo


2 Answers

Try

var Results = DataAdapter.FillSchema(NewData, SchemaType.Source, tableName);

See if that gives you the level of schema detail you need.

like image 84
DWright Avatar answered Oct 08 '22 10:10

DWright


A ResultSet isn't going to know column schema data like that, it would be too intensive an operation to do that per command execution, instead the runtime will create schema information on the fly only using the data it gets back in the data/result-set. For full blown schema you'd have to use something like EF or code the schema yourself. The only thing you can rely on for runtime schema's is the data type (unless the data columns were specifically coded with their attributes).

To properly test for DbNull you do this:

if ( dataRow[colNameOrIndex].Value == DbNull.Value){
    //null
}
like image 40
T McKeown Avatar answered Oct 08 '22 10:10

T McKeown