When using Dapper as follows:
connection.Query("select a from Foo").Select(x => new Foo(x.a, x.b));
My preference is that an exception is thrown when trying to access x.b, rather than it just returning null.
I understand that just returning null may be by design (e.g. for performance reasons), and ideally tests would exist that flag up the missing data, but if I could have both, this seems like an additional layer of safety that may be worth having.
Alternatively, is there another way to instantiate an object using a constructor in a way that will throw an exception when a needed column is missing?
Yup. Dapper often seems to err on the side of optimism. Every error is a runtime error, and as in this case, some things that you would like to be errors fly straight through.
Were you to use QueryFirst, you wouldn't even need to run the program. This would be caught as you type. You access your query results via generated POCOs, so if a column isn't in the query, it isn't in the POCO. If you use
select *, then later delete a columnn from the DB, you can regenerate all your queries and the compile errors will point to the line in your code that tries to access the deleted column.
Short video presentation here.
disclaimer: I wrote QueryFirst