我在这个问题中遇到了完全相同的问题: How to override SQL Server default value constraint on a boolean when inserting new entity? [关闭]
像他一样,我从客户端到控制器获得了布尔值的良好值,false,但_context.SaveChanges();由于 Entity Framework 和数据库中的默认值约束,它通过调用设置为 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
...
}
Run Code Online (Sandbox Code Playgroud)
在我的数据库中:
CREATE TABLE myEntity(
Id INTEGER IDENTITY(1,1) NOT NULL,
...
Active BIT NOT NULL CONSTRAINT DF_myEntity_Active DEFAULT 1
);
Run Code Online (Sandbox Code Playgroud)
在我的控制器中:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id, Active, etc.")] Entity myEntity)
{
if …Run Code Online (Sandbox Code Playgroud) c# sql-server boolean default-constraint entity-framework-core