ModelState.IsValid is false when its Data Model Concurrency Token is non nullable

49 Views Asked by At

When I try to Create a new data line(instance of this data model) it won't create anything. Error message is: "ConcurrencyToken field is required" so ModelState is not valid.

The data model is:

public class ProductCategory
{
    [Display(Name = "Category Number")]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ProductCategoryID { get; set; }

    [StringLength(50, MinimumLength = 3)]
    [Display(Name = "Category Name")]
    public string? Name { get; set; }

    [Timestamp]
    public byte[] ConcurrencyToken { get; set; }

    public ICollection<Product>? Product { get; set; }
}

The Snapshot that this creates is:

b.Property<byte[]>("ConcurrencyToken")
                    .IsConcurrencyToken()
                    .IsRequired()
                    .ValueGeneratedOnAddOrUpdate()
                    .HasColumnType("rowversion");

When creating a new instance the .ValueGeneratedOnAddOrUpdate() is supposed to create a value for the ConcurrencyToken field of type RowVersion to satisfy the .IsRequired() property so that the input will bind to the model, I would think, but it doesn't.

Maybe the .IsRequired() property should be out of there, but if I add the question mark then migrate to make this nullable like this:

public byte[]? ConcurrencyToken { get; set; }

Update-Database gives an error. I didn't show that error here but it is something implying that EF can't convert the data type to [TimeStamp].

There are only two options with the above data property that I know, that is with the "?", or without that. Where else in my code should I be looking so that I can create a data instance?

Now I have solved this. I deleted the <Nullable>enable</Nullable> tag in the .csproj file. My understanding is that the <Nullable>enable</Nullable> tag causes the advanced compiler technology to be more optimistic that variables could be null. While at the same time, if those variables must not be null so as to satisfy the EF framework, and therefore the database needs (that is, to not be null) then the compiler prohibits models from binding unless they are more surely NOT NULL than this developer has made them. Ergo, having '.ValueGeneratedOnAddOrUpdate()' to bind to a variable to a data model will not suffice to satisfy the compiler. Do I have that exactly on the button?

0

There are 0 best solutions below