skip to Main Content

In my server, my field "Name" is marked as [Required] so EntityFramework can mark it as non nullable on the migration:

public class MyClass
{
   [Required]
   public string? CreatedBy {get;set;}
}

But the "CreatedBy" field is set at creation on the server, so the first time it must travel as NULL from the client

So I get a serialization error:

https://tools.ietf.org/html/rfc7231#section-6.5.1

[‘The CreatedBy field is required.’]

How do I declare the CreatedBy field to be null for serialization but non null for database?

2

Answers


  1. Chosen as BEST ANSWER

    Since I don't want to use fluent api for this, I decided to disable the serialization validation:

    program.cs

    builder.Services.AddControllers(
        options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
    
    ...
    
    builder.Services.Configure<ApiBehaviorOptions>(options
        => options.SuppressModelStateInvalidFilter = true);
    
    ...
    
    

  2. Remove the Required-Attribute and set the CreatedBy field as required in OnModelCreating():

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<MyClass>()
            .Property(x => x.CreatedBy)
            .IsRequired();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search