简体   繁体   中英

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.

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 .

How do you migrate ? Clear the table dbo.__MigrationHistory. Very often I experience similar problems with EF, and in most cases cleaning this table helps. (It'll definitely work, I recreate this situation in my computer)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM