Note that there are some explanatory texts on larger screens.

plurals
  1. PO.NET Dapper nullable cast error
    primarykey
    data
    text
    <p>Using .NET Dapper, I am having an issue getting a database field that contains an integer value (0/1) to map to a nullable boolean property in a class.</p> <p>To keep things simple, I have stripped down and renamed the class to the bare minimum needed to reproduce the problem:</p> <pre><code>public class Test { public bool? TestField { get; set; } } </code></pre> <p>If the following code is called to populate the Test class:</p> <pre><code>var Results = DBConnection.Query&lt;Test&gt;("SELECT 0 As TestField]").ToList(); </code></pre> <p>the following error will be thrown:</p> <pre><code>Invalid cast from 'System.Int32' to 'System.Nullable`1[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] </code></pre> <p>If I remove the question mark, making the field a non-nullable boolean (i.e. public <strong>bool</strong> TestField), everything works fine.</p> <p>The immediate answer might appear to remove the nullable and call it a day. However, the reason that won't work is because we are using this same class to serialize records to and from a web service, and we need to be able to tell the difference between false and null. I thought of having two classes, one with nullable property types, and one without, but then I have the added overhead of maintaining two classes instead of one.</p> <p>A custom data transformation during a property set would be ideal. Though, I haven't found anything in the dapper documentation to suggest that this is even possible.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload