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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With