CMorgan
CMorgan

Reputation: 693

Entity Framework Entity Builder not overwriting default value

EDIT May, 18th 2020: This is not solved, but I worked around it.

I use Entity Framework Fluent Api to create domain classes. One of the properties has the mapping HasDefaultValue(true).

When I try to insert data into the database, and setting this property to false, something overrides this and still inserts true in the database.

Entity Builder

public void Configure(EntityTypeBuilder<Shifts> builder)
{
   builder.ToTable("Shifts");

   builder.HasKey(s => s.ID);

   builder.Property(s => s.Available)
     .HasDefaultValue(true);   
}

Controller

Shifts newShift = new Shifts()
{
   Name = shiftOne,
   Available = false,
   // other fields               
};

Now when I save it like this:

_unitOfWork.Shifts.Add(newShift);
await _unitOfWork.Commit();

The debugger shows that my newShift object has a field Available set to false, when hitting the unitOfWork.Shifts.Add(newShift); line.

After the commit, that changes to true all of the sudden, and when I look in the database, I see the field is set to true. Code runs without errors.

How can I prevent this and have the correct value entered?

EDIT with solution: I have removed .HasDefaultValue. Now it works, obviously, but I still don't know what caused the behavior in the first place.

Upvotes: 1

Views: 939

Answers (1)

PK.
PK.

Reputation: 588

I can see 2 ways of fixing your issue:

  1. Make your "Available" property do nullable bool - it should do or
  2. Remove that

    .HasDefaultValue(true)

and add a constructor to your Shifts

public Shifts(){
   Available=true;
}

Upvotes: 2

Related Questions