I got quite the same problem in this question : How to override SQL Server default value constraint on a boolean when inserting new entity? [closed]
Like him, I get the good value of my boolean from the client to the controller, false, but it's set to true by the call of _context.SaveChanges();
because of Entity Framework and the default value constraint in the database.
BUT : I'm using Entity Framework Core and I don't have any [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
annotation to remove to fix the problem.
In my ApplicationDbContext.cs :
modelBuilder.Entity<myEntity>(entity =>
{
entity.Property(e => e.Active).HasDefaultValueSql("1");
//entity.Property(e => e.Active).HasDefaultValueSql<bool>("1"); // doesn't fix
...
}
In my Database :
CREATE TABLE myEntity(
Id INTEGER IDENTITY(1,1) NOT NULL,
...
Active BIT NOT NULL CONSTRAINT DF_myEntity_Active DEFAULT 1
);
In my Controller :
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id, Active, etc.")] Entity myEntity)
{
if (ModelState.IsValid)
{
_context.Add(myEntity); // here myEntity.Active = false
await _context.SaveChangesAsync();
// same problem with _context.SaveChanges(); in another controller
// here myEntity.Active = true
}
...
}
It seems that EF doesn't map C# boolean with SQL bit correctly and always takes the default value. Does somebody have an issue to force the false value ?
Finally I can have data annotations generated in my EF model using --data-annotations
option in the EF command. So I put [DatabaseGenerated(DatabaseGeneratedOption.None)]
on the property and don't use the default contraint of the database.