Skip to content

Commit

Permalink
Add support of nullable types for DataReaderResult.Single<T>() #47
Browse files Browse the repository at this point in the history
  • Loading branch information
VitaliyMF committed May 23, 2018
1 parent fd37c03 commit f1d7899
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/NReco.Data.Tests/DbDataAdapterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ public void Select() {
// count for schema-qualified query
Assert.Equal(5, DbAdapter.Select( new Query( new QTable( "main.contacts",null) ).Select(QField.Count) ).Single<int>() );

// select single that is null
Assert.False( DbAdapter.Select( new Query("companies", (QField)"id">(QConst)1000).Select(new QField("sum", "sum(size)")) ).Single<int?>().HasValue );
Assert.Equal(0, DbAdapter.Select(new Query("companies", (QField)"id" > (QConst)1000).Select(new QField("sum", "sum(size)"))).Single<int>() );

// count: data view
Assert.Equal(5, DbAdapter.Select(new Query("contacts_view").Select(QField.Count) ).Single<int>() );

Expand Down
6 changes: 5 additions & 1 deletion src/NReco.Data/Result/DataReaderResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,9 @@ public DataTable ToDataTable(DataTable tbl) {
#endif

private T ChangeType<T>(object o, TypeCode typeCode) {
if (DataHelper.IsNullOrDBNull(o)) {
return default(T);
}
return (T)Convert.ChangeType(o, typeCode, System.Globalization.CultureInfo.InvariantCulture);
}

Expand All @@ -248,7 +251,8 @@ private Dictionary<string, object> ReadDictionary(IDataReader rdr) {
}

private T Read<T>(IDataReader rdr) {
var typeCode = Type.GetTypeCode(typeof(T));
var undelyingType = Nullable.GetUnderlyingType(typeof(T));
var typeCode = Type.GetTypeCode(undelyingType ?? typeof(T));
// handle primitive single-value result
if (typeCode!=TypeCode.Object || typeof(T)==typeof(object)) {
if (rdr.FieldCount==1) {
Expand Down

0 comments on commit f1d7899

Please sign in to comment.