是否有“优雅”的方式给特定的属性一个默认值?
也许是DataAnnotations,比如:
[DefaultValue("true")]
public bool Active { get; set; }
谢谢你!
是否有“优雅”的方式给特定的属性一个默认值?
也许是DataAnnotations,比如:
[DefaultValue("true")]
public bool Active { get; set; }
谢谢你!
当前回答
你的模型属性不必是“自动属性”,即使那样更简单。而DefaultValue属性实际上只是提供信息的元数据 这里接受的答案是构造函数方法的一种替代方法。
public class Track
{
private const int DEFAULT_LENGTH = 400;
private int _length = DEFAULT_LENGTH;
[DefaultValue(DEFAULT_LENGTH)]
public int LengthInMeters {
get { return _length; }
set { _length = value; }
}
}
vs.
public class Track
{
public Track()
{
LengthInMeters = 400;
}
public int LengthInMeters { get; set; }
}
这只适用于使用这个特定类创建和消费数据的应用程序。如果数据访问代码是集中的,通常这不是问题。要跨所有应用程序更新该值,需要配置数据源以设置默认值。Devi的回答展示了如何使用迁移、sql或数据源使用的任何语言来实现这一点。
其他回答
你的模型属性不必是“自动属性”,即使那样更简单。而DefaultValue属性实际上只是提供信息的元数据 这里接受的答案是构造函数方法的一种替代方法。
public class Track
{
private const int DEFAULT_LENGTH = 400;
private int _length = DEFAULT_LENGTH;
[DefaultValue(DEFAULT_LENGTH)]
public int LengthInMeters {
get { return _length; }
set { _length = value; }
}
}
vs.
public class Track
{
public Track()
{
LengthInMeters = 400;
}
public int LengthInMeters { get; set; }
}
这只适用于使用这个特定类创建和消费数据的应用程序。如果数据访问代码是集中的,通常这不是问题。要跨所有应用程序更新该值,需要配置数据源以设置默认值。Devi的回答展示了如何使用迁移、sql或数据源使用的任何语言来实现这一点。
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属性不会自动设置属性的值,你必须自己设置
Entity Framework Core Fluent API HasDefaultValue方法用于指定映射到属性的数据库列的默认值。该值必须为常数。
public class Contact
{
public int ContactId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public bool IsActive { get; set; }
public DateTime DateCreated { get; set; }
}
public clas SampleContext : DbContext
{
public DbSet<Contact> Contacts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Context>()
.Propery(p => p.IsActive)
.HasDefaultValue(true);
}
}
Or
喜欢它!
你也可以指定一个SQL片段来计算默认值:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.Created)
.HasDefaultValueSql("getdate()");
}