Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy am I getting a "Nullable object must have a value" exception when I'm using Condition?
    primarykey
    data
    text
    <p>I'm getting a "Nullable object must have a value" in the example code below. Why do I need the following fix to make this work:</p> <pre><code>.ForMember(dest =&gt; dest.ShirtColor, dest =&gt; dest.MapFrom(src =&gt; src.ShirtColor != null ? new OptionSetValue((int) src.ShirtColor) : null)) </code></pre> <pre class="lang-cs prettyprint-override"><code>AutoMapper.Mapper.CreateMap&lt;PersonA, PersonB&gt;() .ForMember(dest =&gt; dest.FirstName, dest =&gt; dest.MapFrom(src =&gt; src.FirstName)) .ForMember(dest =&gt; dest.LastName, dest =&gt; dest.MapFrom(src =&gt; src.LastName)) // Condition to avoid overwriting existing data!!! .ForMember(dest =&gt; dest.ShirtColor, dest =&gt; dest.Condition(src =&gt; src.ShirtColor != null)) .ForMember(dest =&gt; dest.ShirtColor, dest =&gt; dest.MapFrom( src =&gt; new OptionSetValue((int)src.ShirtColor))) // Fix that should not be needed due to condition: //.ForMember(dest =&gt; dest.ShirtColor, // dest =&gt; dest.MapFrom( // src =&gt; src.ShirtColor != null // ? new OptionSetValue((int) src.ShirtColor) // : null)); PersonA source = new PersonA(); source.FirstName = "Thomas"; source.LastName = "Jefferson"; source.ShirtColor = null; // nullable int PersonB destination = new PersonB(); destination.FirstName = "Thomas"; destination.LastName = "Jefferson"; destination.ShirtColor = new OptionSetValue(4); // Results in: "Nullable object must have a value" despite the fact that // condition should have been met! Mapper.Map&lt;PersonA, PersonB&gt;(source, destination); Debug.Assert(destination.ShirtColor != null); Console.WriteLine("Our existing data was not overwritten!!"); Console.WriteLine("Hit enter to exit"); Console.ReadLine(); </code></pre> <p>Here is how OptionSet is defined: public class OptionSetValue { public OptionSetValue(){}</p> <pre class="lang-cs prettyprint-override"><code> public OptionSetValue(int value) { Number = value; } public int Number { get; set; } } </code></pre>
    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.
 

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