Home > Enterprise >  Foreign Key Reference Object being required in Entity Framework
Foreign Key Reference Object being required in Entity Framework

Time:08-07

I'm building an API in C# (.NET Core 6) and Entify Framework.

My models are like this:

public class Category 
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; } = null!;
}

public class Product 
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; } = null!;
    [Column("cat_id")]
    [ForeignKey("CategoryRef")]
    public int CategoryId { get; set; };
    public virtual Category CategoryRef { get; set; } = null!;
}

However, when I try to post a new Product like this:

{
   "Name": "My product",
   "CategoryId": 1
}

I get the following error:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-d1c8543428cbcf765f7f5610cfbe0fdf-e2d9938fe33e3aab-00",
  "errors": {
    "CategoryRef": [
      "The CategoryRef field is required."
    ]
  }
}

If I comment out the CategoryRef line (and the foreign key that points to it), it works fine (I have an existing Category in the database with Id = 1).

What am I doing wrong?

CodePudding user response:

I solved it by adding:

builder.Services.AddControllers(options => 
    options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
  • Related