是否有“优雅”的方式给特定的属性一个默认值?

也许是DataAnnotations,比如:

[DefaultValue("true")]
public bool Active { get; set; }

谢谢你!


当前回答

我做了什么,我在实体的构造函数中初始化了值

注意:DefaultValue属性不会自动设置属性的值,你必须自己设置

其他回答

using System.ComponentModel;

[DefaultValue(true)]

public bool Active { get; set; }

很简单!只需要注释required即可。

[Required]
public bool MyField { get; set; }

迁移的结果将是:

migrationBuilder.AddColumn<bool>(
name: "MyField",
table: "MyTable",
nullable: false,
defaultValue: false);

如果希望为true,请在更新数据库之前在迁移中将defaultValue更改为true

假设您有一个名为Products的类名,并且有一个IsActive字段。你只需要一个create构造函数:

Public class Products
{
    public Products()
    {
       IsActive = true;
    }
 public string Field1 { get; set; }
 public string Field2 { get; set; }
 public bool IsActive { get; set; }
}

那么您的IsActive默认值为True!

Edite:

如果你想用SQL来执行这个命令:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Blog>()
        .Property(b => b.IsActive)
        .HasDefaultValueSql("true");
}

在。net Core 3.1中,你可以在模型类中做以下事情:

    public bool? Active { get; set; } 

在DbContext OnModelCreating中添加默认值。

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Foundation>()
            .Property(b => b.Active)
            .HasDefaultValueSql("1");

        base.OnModelCreating(modelBuilder);
    }

在数据库中产生如下结果

注意: 如果你的属性没有nullable (bool?),你会得到以下警告

The 'bool' property 'Active' on entity type 'Foundation' is configured with a database-generated default. This default will always be used for inserts when the property has the value 'false', since this is the CLR default for the 'bool' type. Consider using the nullable 'bool?' type instead so that the default will only be used for inserts when the property value is 'null'.

我做了什么,我在实体的构造函数中初始化了值

注意:DefaultValue属性不会自动设置属性的值,你必须自己设置