gpt4 book ai didi

c# - 如何使用 Entity Framework Core 在具有默认值的 boolean 值上设置另一个值?

转载 作者:太空狗 更新时间:2023-10-30 01:32:02 25 4
gpt4 key购买 nike

我在这个问题上遇到了完全相同的问题: How to override SQL Server default value constraint on a boolean when inserting new entity? [closed]

像他一样,我从客户端到 Controller 获得了我的 boolean 值的好值,false,但是由于 Entity Framework 和数据库中的默认值约束。

但是:我正在使用 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
);

在我的 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
}
...
}

似乎 EF 没有正确映射 C# boolean 值和 SQL 位,并且始终采用默认值。有人有强制使用错误值的问题吗?

最佳答案

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

如果您将 bool 值设置为可为空,然后使用 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);

当您向数据库中插入新记录时,您不需要在对象声明中指定 boolean 属性。下面,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();

关于c# - 如何使用 Entity Framework Core 在具有默认值的 boolean 值上设置另一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38570246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com