我在这个问题中遇到了同样的问题: How to override SQL Server default value constraint on a boolean when inserting new entity? [关闭]
像他一样,我从客户端到控制器获得了良好的布尔值,false,但_context.SaveChanges();
由于实体框架和数据库中的默认值约束,它通过调用设置为 true。
但是:我正在使用 Entity Framework Core,我没有任何[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
注释要删除来解决问题。
在我的 ApplicationDbContext.cs 中:
modelBuilder.Entity<myEntity>(entity =>
{
entity.Property(e => e.Active).HasDefaultValueSql("1");
//entity.Property(e => e.Active).HasDefaultValueSql<bool>("1"); // doesn't fix
...
}
在我的数据库中:
CREATE TABLE myEntity(
Id INTEGER IDENTITY(1,1) NOT NULL,
...
Active BIT NOT NULL CONSTRAINT DF_myEntity_Active DEFAULT 1
);
在我的控制器中:
[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
}
...
}
似乎 EF 没有正确地将 C# 布尔值与 SQL 位映射,并且始终采用默认值。有人有强制错误值的问题吗?