I Love Stackoverflow
I Love Stackoverflow

Reputation: 6868

Specified cast is not valid while fetching column details from SQL Server

I am trying to fetch following details of columns from SQL Server:

I am successfully getting data when I have below schema for table:

Table1:

Col1 : varchar(40),null)
Col2 : varchar(2,null)
Col3 : varchar(57,null)
Col4 : varchar(245 ,null)
Col5 : datetime(not null)

But I'm getting an error

Specified cast is not valid.

in case of this schema:

Col1 : varchar(34,null)
Col2 : varchar(1066,null)
Col3 : varchar(500,null)
Col4 : varchar(600,null)
Col5 : numeric(31,13,null)
Col6 : numeric(31,13,null)
Col7 : datetime(null)

Code:

String[] columnRestrictions = new String[4];
columnRestrictions[0] = 'MyDb';
columnRestrictions[1] = 'dbo';
columnRestrictions[2] = 'Employee';

using (SqlConnection con = new SqlConnection("MyConnectionString"))
{
    con.Open();
    var columns = con.GetSchema("Columns", columnRestrictions).AsEnumerable()
         .Select
          (
                 t => new 
                 {
                     Name = t[3].ToString(),
                     Datatype = t.Field<string>("DATA_TYPE"),
                     IsNullable = t.Field<string>("is_nullable"),
                     Size = t.Field<int?>("character_maximum_length"),
                     NumericPrecision = t.Field<int?>("NUMERIC_PRECISION"), //error on this field
                     NumericScale = t.Field<int?>("NUMERIC_SCALE")
                 }).ToList();

Source :

Reference1

Reference2

Update: this line is causing the issue

NumericPrecision = t.Field<int?>("NUMERIC_PRECISION"), //error on this field

How can I resolve this error and fetch size, precision and scale for columns?

Upvotes: 0

Views: 957

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460068

The problem in your code is that you are casting a byte to int?, the Field-method supports nullable types (if the column can be null), but it doesn't convert from byte? to int?. It throws this exception instead. Source

So just use this:

NumericPrecision = t.Field<byte?>("NUMERIC_PRECISION"),

You can always look at the DataColumn's DataType property.

Upvotes: 2

Related Questions