.NET Core WebAPI ODATA: The xxx field is required - foreign key updates NOT a bug :-)

Just a short note. If you encounter the following message during insert/update calls to your WebAPI REST endpoint:

"message": "Resources[0].ResourceFile:\r\nThe ResourceFile field is required.\r\n\r\nResources[0].WebSiteProject:\r\nThe WebSiteProject field is required.", "details": [ { "code": "", "target": "Resources[0].ResourceFile", "message": "The ResourceFile field is required." },

This error occurs often when the model class contains one or more foreign key relations and the referenced object property is not nullable. The following code demonstarte the issue

public class WebSiteResource
{
  [Key]
  public uint ID { get; set; }
  public uint ResourceFileID { get; set; }
  public uint WebSiteProjectID { get; set; }
  public ResourceFile ResourceFile { get; set; }
  public WebSiteProject WebSiteProject { get; set; }
}

The model class contains the two foreign key properties ResourceFile and WebSiteProject. In case the post request to insert a new entry conatains only the ID-field properties the above explained error will be thrown. To solve this just marked the properties as nullable. See the corrected code below:

public class WebSiteResource
{
  [Key]
  public uint ID { get; set; }
  public uint ResourceFileID { get; set; }
  public uint WebSiteProjectID { get; set; }
  public ResourceFile? ResourceFile { get; set; }
  public WebSiteProject? WebSiteProject { get; set; }
}

Happy coding 😊

Kommentare

Beliebte Posts aus diesem Blog

Exchange Online: Schutzregel für E-Mail Weiterleitung

Vertikaler Bereich deaktiviert

Connect-SPOService: The remote server returned an error: (400) Bad Request