Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation failed for one or more entities in Entity Framework for nullable boolean property

My class looks like this, I added new property IsModified which can be nullable. I can create a new entity of type A using only Name and Key property, but when I try to update key for any existing records for which IsModified is null in db, I get this error from Entity Framework:

System.Data.Entity.Validation.DbEntityValidationException. The IsModified field is required on context.SaveChangesAsync().

Model class:

public class A
{
    public long ID { get; set; }
    public string Key { get; set; }
    public bool? IsModified { get; set; }
    public string Name { get; set; }

    public A()
    {
        this.IsModified = false;
    }
}

SQL Server table:

CREATE TABLE [dbo].[A]
(
    [ID] [bigint] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](max) NOT NULL,
    [Key] [nvarchar](max) NOT NULL,
    [IsModified] [bit] NULL,
 )

I am using Entity Framework v6 with a code-first approach. [IsModified] is nullable, so I am not sure why the field is still required.

like image 317
user3014311 Avatar asked Aug 08 '18 06:08

user3014311


1 Answers

The issue here was boolean value cannot be configured as null. It will always be considered required by EF. I changed IsModified bit null to IsModified bit not null default 1 .And updated the existing records with default value using Migration. Reference - https://docs.microsoft.com/en-us/ef/core/modeling/required-optional.

like image 108
user3014311 Avatar answered Oct 03 '22 06:10

user3014311