是否有“优雅”的方式给特定的属性一个默认值?
也许是DataAnnotations,比如:
[DefaultValue("true")]
public bool Active { get; set; }
谢谢你!
是否有“优雅”的方式给特定的属性一个默认值?
也许是DataAnnotations,比如:
[DefaultValue("true")]
public bool Active { get; set; }
谢谢你!
当前回答
using System.ComponentModel;
[DefaultValue(true)]
public bool Active { get; set; }
其他回答
在。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(true)]
public bool IsAdmin { get; set; }
我以为他们只是犯了加引号的错误…但遗憾的是,没有这样的直觉。其他建议对我来说太多了(假设我有进入表并进行更改所需的特权……并不是每个开发者在任何情况下都会这么做)。最后我还是用老办法做了。我在SQL Server表中设置了默认值…我的意思是真的,已经够了!注意:我进一步测试了添加-迁移和更新-数据库,更改卡住了。
假设您有一个名为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");
}
using System.ComponentModel;
[DefaultValue(true)]
public bool Active { get; set; }
我发现,只需在实体属性上使用Auto-Property Initializer就足以完成工作。
例如:
public class Thing {
public bool IsBigThing{ get; set; } = false;
}