gpt4 book ai didi

c# - 如何在 Code First 模型中设置 bool 值的默认值?

转载 作者:行者123 更新时间:2023-12-03 03:11:25 25 4
gpt4 key购买 nike

我有一个现有的表/模型,我想在其中添加一个新的 bool 列。该表已经有数百行数据,我无法触及现有数据。但是.. 该列不能为空,因此我需要为当前存在的所有行提供默认值 true

public class Revision
{
...
public Boolean IsReleased { get; set; }
....
}

重要:

(这是在OP中,但人们似乎错过了。)

当数据库通过迁移进行更新时,接收此新列的所有现有行必须将其值设置为 True。

最佳答案

您可以避免使用字段并利用 Auto-property initialization ,C# 6 中的一项新功能。

当列添加到数据库时,这会将默认值设置为 true

public class Revision
{
...
public Boolean IsReleased { get; set; } = true;
....
}

编辑以包含@BrewMatecomment :

If all of your values set to false when you update the database, make sure to have the JSON formatter handle default values. The JSON formatter will ignore default values by default and then your database is setting the boolean to its default value, false. See the link below, I would try Default as the enumeration: http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DefaultValueHandling.htm

关于c# - 如何在 Code First 模型中设置 bool 值的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40936566/

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