简体   繁体   中英

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.

Try

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

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM