Default value for non-nullable value type with a custom type converter throws exception

Posts   
 
    
tomcap
User
Posts: 15
Joined: 03-Apr-2017
# Posted on: 01-Feb-2021 21:03:08   

LLBLGen 5.6.1; Database First, Adapter

Some of the fields in my tables use a type converter for a custom value type (struct). If I instantiate one of these entities and access the property that is assigned the custom value type it throws a null reference exception. It is quite obvious why this is happening; the TypeDefaultValue.GetDefaultValue method in the generated code (HelperClasses) does not include the custom value type in its switch statement. What is the correct way of dealing with this situation? Currently I just added the custom value type to the switch statement. However, this will need to be done every time the code is regenerated. Is there a cleaner way of doing this?

I apologize if I missed something that is documented.

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39614
Joined: 17-Aug-2003
# Posted on: 02-Feb-2021 10:37:27   

there are some options:

  • Use a custom version of the template, which means creating a custom TemplateBindings file, give it a higher precedence than 10 (which the default template bindings use) and bind a new template to the ID: SD_TypeDefaultValueIncludeTemplate. Currently the file SharedTemplates\Net3.5\C#\typeDefaultValueInclude.template is bound to that. See https://www.llblgen.com/Documentation/5.7/Designer/How%20Toworkwithtemplates.htm. This can be a cumbersome task.
  • Override in a partial class of the entity/entities in question, in a separate folder, and override the method CreateTypeDefaultValueProvider(). There you instantiate your own variant of the generated TypeDefaultValue class so you copy that class, add your changes and instantiate that class instead of the default one which is instantiated by the CommonEntityBase class.
  • Override in a partial class of CommonEntityBase (in a separate folder) the method PostProcessValueToGet. In there you check whether valueToReturn is null and the passed in fieldInfo.DataType is of your struct type. If so, return the default value you want, otherwise simply do nothing.

I think the last option is preferable: least amount of work and easiest to maintain.

Frans Bouma | Lead developer LLBLGen Pro