Trying to avoid creating separate DTOs for my one really simple post in this app. I have a required property on my entity that is a reference to another entity. This is the user, which is grabbed later by the authentication/authorization and populated.
Except... I can't get past the instantiation in the controller because it's a non-nullable property.
public class MyModel {
public UserModel User { get; set; } = null!;
}
public IActionResult Submit(MyModel model){
model.User = CurrentUser; // <- can't get here.
}
0: "The User field is required."
I was under the impression that the = null!
would allow the model to instantiate and not care that it's "null
" until I try to utilize it later? I may be misunderstanding that functionality significantly.
I'd very much like to:
- Keep this property not-nullable.
- Not have to create a second class to handle post data without this property
Is this possible?
CodePudding user response:
You would need to initialize the property to some valid value. The point of non-nullable is that it can never be null.
My only suggestions would be to either
- let the value be null, and initialize as such, but edit set operator to throw ArgumentNullException if given null value later,
- define
User.Null
to be a non-existentUser
, used for "initialization", or - change your class to enable passing value to UserModel during initialization and create MyModel in Submit as output parameter.
CodePudding user response:
You can work with a default value.
If the instance you are receiving is null, it will create a new instance of User
, else it will contain your non-null instance.
public class MyModel {
public UserModel User { get; set; } = new User();
}
CodePudding user response:
What if you use a property with a backing field?
public class MyModel {
[CanBeNull]
private UserModel _User = null;
public UserModel User
{
get { return _User ?? throw new System.InvalidOperationException("_User is has not been set yet"); }
set { _User = value; }
}
}
CodePudding user response:
You are probably using Net 6. You can remove option nullable from project configuration. This way you don't need to do a stupid job to mark all default nullabble properties all your classes as nullable
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>disable</Nullable> <!-- change from enable -->
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>