5

我在这个问题中遇到了同样的问题: 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 位映射,并且始终采用默认值。有人有强制错误值的问题吗?

4

3 回答 3

7

我认为您不能使用annotations设置默认值。但是,在自己研究了这个问题后,我发现了一个相当棘手的解决方法。

如果您将布尔值设置为可为空,然后使用 fluent api 设置默认值,您应该没问题。它并不完美,但它有效:

public class Year
{
        public int Id { get; set; }
        public string label { get; set; }
        public int year { get; set; }
        public bool? active { get; set; }
}

然后,在您的数据上下文中,设置默认值:

            modelBuilder.Entity<Year>()
            .Property("active")
            .HasDefaultValue(true);

当您将新记录插入数据库时​​,您无需在对象声明中指定布尔属性。下面,2017 年的默认值为 true。

            var newYears = new List<Year>();

            newYears.Add(new Year { label = "2019", year = 2019, active = false });
            newYears.Add(new Year { label = "2018", year = 2018, active = true });
            newYears.Add(new Year { label = "2017", year = 2017});
            _context.Years.AddRange(newYears);
            _context.SaveChanges();
于 2018-07-09T20:26:55.893 回答
3

我也遇到了可空的布尔值几乎类似的问题。我在 Sqlite db 之上使用 EF。对我来说,更新值 true/false 没有反映在数据库中。在我覆盖了 OnModelCreating 方法并配置了如下属性之后

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyEntity>()
        .Property(p => p.IsActive).ValueGeneratedNever().HasDefaultValue(null);
    }

在此更改后,值已按预期更新。希望这也可以帮助你。

于 2017-04-09T04:48:26.120 回答
0

--data-annotations最后,我可以使用EF 命令中的选项在我的 EF 模型中生成数据注释。所以我放[DatabaseGenerated(DatabaseGeneratedOption.None)]了属性,不使用数据库的默认约束。

于 2016-12-22T08:22:57.833 回答