craftsman
craftsman copied to clipboard
Enable nullability in generated projects
It would be nice if <Nullable>enable</Nullable> was automatically set in the generated csproj. Recent .NET versions are pushing hard to making this the default everywhere (the billion dollar mistake), and I noticed it only required minor changes to enable this in my project after the fact.
Some things to take into account if you do this, though:
- Entity fields such as
BaseEntity.CreatedByneed to becomestring?so nullability is now explicit, and EF will make these fields non-null otherwise now. This also applies to fields in general, but this is probably what you want (non-null database field for non-nullable C# property). - .NET will start validating non-nullable DTO fields as
Requiredin the API automatically; omitting these fields in the request body will generate Bad Request errors, which is probably what you want and doesn't happen currently (e.g. omitting a field inPUTwill have the same effect as explicitly setting it tonull, which was misleading to me the first time and probably will be to other clients, too).- Similarly,
FooParametersDtoneeds to makeFiltersandSortOrderastring?or they will always be required. - Ironically, adding
[Required]attribute (not automatically added currently) is still useful or the OpenAPI specification won't mark the field as required despite .NET validating them at runtime.
- Similarly,
- Every DTO with non-nullable fields will spawn warnings about the fields potentially being
nullbecause there is no constructor and they can be fetched throughgetwithout setting them first throughset. With .NET 7 you can do e.g.public required string FirstName { get; set; }to fix this if you don't want to spawn constructors everywhere.
Yup this is on my list. Should be simple, just need to do it!