Found this issue while migrating code from .NET Framework 4.8 to .NET Core 3. Calling .Field
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?
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.
Most helpful comment
Thanks for the issue and the repro, I'll take a look at this in the coming days.