Reputation: 448
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.
Upvotes: 7
Views: 554
Reputation: 448
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://learn.microsoft.com/en-us/ef/core/modeling/required-optional.
Upvotes: 2
Reputation: 984
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)
Upvotes: 0