Skip to content

Commit 4c6b9f7

Browse files
committed
Handle optional properties in model From method
Updated the From method in the model template to check for the existence of optional properties in the input map before assigning values. This prevents errors when optional properties are missing from the input dictionary. (for examle in model: User, :-/ )
1 parent b44f0b1 commit 4c6b9f7

File tree

1 file changed

+3
-1
lines changed

1 file changed

+3
-1
lines changed

templates/dotnet/Package/Models/Model.cs.twig

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ namespace {{ spec.title | caseUcfirst }}.Models
3939
public static {{ definition.name | caseUcfirst | overrideIdentifier }} From(Dictionary<string, object> map) => new {{ definition.name | caseUcfirst | overrideIdentifier }}(
4040
{%~ for property in definition.properties %}
4141
{{ property.name | caseCamel | escapeKeyword | removeDollarSign }}:{{' '}}
42+
{%- if not property.required -%}map.ContainsKey("{{ property.name }}") ? {% endif %}
4243
{%- if property.sub_schema %}
4344
{%- if property.type == 'array' -%}
4445
((IEnumerable<object>)map["{{ property.name }}"]).Select(it => {{ property.sub_schema | caseUcfirst | overrideIdentifier }}.From(map: (Dictionary<string, object>)it)).ToList()
@@ -60,6 +61,7 @@ namespace {{ spec.title | caseUcfirst }}.Models
6061
{%~ endif %}
6162
{%~ endif %}
6263
{%~ endif %}
64+
{%- if not property.required %} : null{% endif %}
6365
{%- if not loop.last or (loop.last and definition.additionalProperties) %},
6466
{%~ endif %}
6567
{%~ endfor %}
@@ -96,4 +98,4 @@ namespace {{ spec.title | caseUcfirst }}.Models
9698
{%~ endif %}
9799
{%~ endfor %}
98100
}
99-
}
101+
}

0 commit comments

Comments
 (0)