C
C#6d ago
schwartzmj

OpenAPI generating nullable type. Additionally Dictionary value set as "any"

c#
public sealed record MyDto {
public required List<MyType> MyList { get; init; }

public Dictionary<int, MyType> MyDictionary =>
MyList.ToDictionary(
x => x.Id,
x => x
);
}
c#
public sealed record MyDto {
public required List<MyType> MyList { get; init; }

public Dictionary<int, MyType> MyDictionary =>
MyList.ToDictionary(
x => x.Id,
x => x
);
}
There are two issues with this. One is that I cannot make this computed property required because it is computed. Because of this it always shows up as nullable in the OpenApi schema. (Also if it is required it needs to be initialized when creating the record, which I don't want) I cannot add the [Required] attribute because it throws an error if there is no setter. I cannot have a setter because it is computed. The second issue is that it also sets the type as Dictionary<int,any> in the OpenApi schema. I'm hoping that if I can make this "required" it will fix that as well. I'm having this same "nullable" issue with other things like a computed string, not just the dictionary example.
3 Replies
Anton
Anton6d ago
make it required and not computed make a factory function that creates the dto and then initializes that previously computed property make it take in a version of the dto without that property
schwartzmj
schwartzmjOP5d ago
appreciate the feedback. unfortunate if all that code is needed just to get my OpenApi doc to say a field is never null
Anton
Anton5d ago
dtos shouldn't have computed properties in general

Did you find this page helpful?