简体   繁体   中英

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.

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;
}

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