Runtime: System.InvalidCastException on calling System.Data.DataRowExtensions.Field for nullable enums

Created on 18 Oct 2019  路  2Comments  路  Source: dotnet/runtime

Found this issue while migrating code from .NET Framework 4.8 to .NET Core 3. Calling .Field works on both, but .Field throws under .NET Core 3:

An exception of type 'System.InvalidCastException' occurred in System.Data.Common.dll but was not handled in user code: 'Unable to cast object of type 'System.Int32' to type 'System.Nullable`1[corefxissue.MyEnum]'.'
   at System.Data.DataRowExtensions.UnboxT`1.ReferenceOrNullableField(Object value)
   at System.Data.DataRowExtensions.Field[T](DataRow row, String columnName)
   at corefxissue.Tests.RowWithNullableEnum()

This issue occurs when using a DataTable from a DataSet that was filled by System.Data.Common.DbDataAdapter.Fill, but here's a minimal example that breaks the same way:

var table = new DataTable();
var type = typeof(MyEnum?);
table.Columns.Add(new DataColumn("col", Nullable.GetUnderlyingType(type) ?? type));
var row = table.NewRow();
row["col"] = MyEnum.Foo;
table.Rows.Add(row);

var resultFromInt = (MyEnum?)table.Rows[0].Field<int?>("col"); // works
var resultFromEnum = table.Rows[0].Field<MyEnum?>("col"); // throws

Are nullable enums no longer supported in .Field?

area-System.Data bug

Most helpful comment

Thanks for the issue and the repro, I'll take a look at this in the coming days.

All 2 comments

Thanks for the issue and the repro, I'll take a look at this in the coming days.

@my0n this is indeed a bug in corefx, PR dotnet/corefx#42119 is out and will hopefully make it into 3.1.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

aggieben picture aggieben  路  3Comments

bencz picture bencz  路  3Comments

yahorsi picture yahorsi  路  3Comments

matty-hall picture matty-hall  路  3Comments

jchannon picture jchannon  路  3Comments