Ormlite dynamic select failing with Nullable columns

Hi. I am writing some groupby/select max queries in Ormlite, but notice that the dynamic select functionality fails if any of the columns in the dynamic selec are null. Repro:

	[Fact]
public void TestStuff()
{
	Db.CreateTableIfNotExists<ParentTbl>();
	Db.Delete<ParentTbl>();
	Db.Insert(new ParentTbl { DateOfBirth = DateTime.Today });
	Db.Insert(new ParentTbl { DateOfBirth = null });

	// This works fine, both records are returned
	var results = Db.Select<ParentTbl>();

	var q = Db.From<ParentTbl>();
	try
	{
		// Will fail with System.NullReferenceException: 'Object reference not set to an instance of an object.'
		var dynamicResults1 = Db.Select<(int, DateTime)>(q);
	}
	catch (Exception) { /* we failed here! */ }

	try
	{
		// Use of nullable Datetime? doesnt help, same error as above.
		var dynamicResults2 = Db.Select<(int, DateTime?)>(q);
	}
	catch (Exception) { /* we failed here! */ }
}

public class ParentTbl
{
	[AutoIncrement]
	public int Id { get; set; }

	public DateTime? DateOfBirth { get; set; }
}

Further (more complicated) example, whereby join operation fails with “Unable to cast object of type System.DBNull to type System.Datetime”, which I am guessing is for similar reasons as above:

public class ParentTbl
{
	[AutoIncrement]
	public long Id { get; set; }

	public DateTime? DateMarried { get; set; }

	[Reference]
	public List<ChildTbl> Childs { get; set; } = new List<ChildTbl>();
}

public class ChildTbl
{
	[AutoIncrement]
	public long Id { get; set; }

	[References(typeof(ParentTbl))]
	public long ParentId { get; set; }

	public DateTime? DateOfDeath { get; set; }
}


[Fact]
public void TestStuffMore()
{
	Db.DropTable<ChildTbl>();
	Db.DropTable<ParentTbl>();
	Db.CreateTableIfNotExists<ParentTbl>();
	Db.CreateTableIfNotExists<ChildTbl>();
	Db.Delete<ChildTbl>();
	Db.Delete<ParentTbl>();
	var parentTbl = new ParentTbl { DateMarried = DateTime.Today };
	parentTbl.Id = Db.Insert(parentTbl, true);
	Db.Insert(new ChildTbl { ParentId = parentTbl.Id, DateOfDeath = null });

	var q = Db.From<ChildTbl>()
		.RightJoin<ChildTbl, ParentTbl>((c, p) => c.ParentId == p.Id || c.Id == null)
		.GroupBy<ParentTbl>((p) => new { p.Id })
		.Select<ChildTbl, ParentTbl>((c, p) => new { p.Id, MaxKeyValuePeriodEnd = Sql.Max(c.DateOfDeath) });

	var theSqlStatement = q.ToSelectStatement();

	// This will fail with error: System.InvalidCastException: 'Unable to cast object of type 'System.DBNull' to type 'System.DateTime'.'
	var results = Db.Select<(long, DateTime)>(q); 
}

Should be fixed with this commit from v5.1.1 that’s now available on MyGet.

1 Like