Home > Mobile >  ODataController, if the model is incorrect, it gets null on post
ODataController, if the model is incorrect, it gets null on post

Time:12-04

If there is any wrong property (For example if I send the payload data, Person_ instead of Person), model fully gets as null (Post([FromBody] Request data))

public class Person
{
   public Guid Id { get; set; }

   public string? Firstname { get; set; }
 
   public string? Lastname { get; set; }
}

public class Request
{
   public Guid Id { get; set; }

   public Guid? Personid { get; set; }

   public virtual Person? Person { get; set; }
}


 
public IActionResult Post([FromBody] Request data)
{
   ...
}

 
curl --location --request POST 'https://localhost:7124/v2/request?$expand=Person($select=Id,Firstname,Lastname)/Request&@odata.context='https://localhost:7124/v2/$metadata' \
--header 'Content-Type: application/json' \
--data-raw '{
    "Id": "a436677a-fa4b-465e-8e70-211a1a3de8e9",
    "Personid": "be9b53ad-4dfb-4db5-b269-32669f7c4e2d",
    "Person_" : {
        "Firstname": "JOHN",
        "Lastname": "SMITH",
    } 
}'

I need to get the model even though some properties not correct according to model schema.

What could be the reason for it being null?

CodePudding user response:

The reason why the Person property of the Request model is null in your code is because you are using the nullable reference type syntax (string?) for the Firstname and Lastname properties of the Person model. This means that these properties are allowed to be null, and if they are null, the Person property will also be null.

To fix this issue, you can either remove the nullable reference type syntax from the Firstname and Lastname properties, or you can make sure that the JSON request body includes values for these properties.

Here is an example of how you might fix this issue by removing the nullable reference type syntax from the Firstname and Lastname properties:

public class Person
{
   public Guid Id { get; set; }

   public string Firstname { get; set; }

   public string Lastname { get; set; }
}

Alternatively, you can fix this issue by making sure that the JSON request body includes values for the Firstname and Lastname properties of the Person model. Here is an example of how the JSON request body might look in this case:

{
    "Id": "a436677a-fa4b-465e-8e70-211a1a3de8e9",
    "Personid": "be9b53ad-4dfb-4db5-b269-32669f7c4e2d",
    "Person": {
        "Firstname": "JHON",
        "Lastname": "SMITH"
    } 
}

CodePudding user response:

The problem is the declaration of Person in the class Request, It should be public Person Person_ { get; set; }.

You can declare it as public virtual Person? Person_ { get; set; } also if you don't want to change the declaration.

The only catch here is the suffix underscore before Person.

If you don't want to change the declaration then you can use JsonProperty

[JsonProperty("Person_")]
public virtual Person? Person { get; set; }
  • Related