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

也许是DataAnnotations,比如:

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

谢谢你!


当前回答

我承认我的方法脱离了“代码优先”的概念。但是如果你有能力改变表本身的默认值…这比你上面要经历的长度要简单得多……我就是懒得做那些工作!

海报上最初的想法似乎是可行的:

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

我以为他们只是犯了加引号的错误…但遗憾的是,没有这样的直觉。其他建议对我来说太多了(假设我有进入表并进行更改所需的特权……并不是每个开发者在任何情况下都会这么做)。最后我还是用老办法做了。我在SQL Server表中设置了默认值…我的意思是真的,已经够了!注意:我进一步测试了添加-迁移和更新-数据库,更改卡住了。

其他回答

你的模型属性不必是“自动属性”,即使那样更简单。而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或数据源使用的任何语言来实现这一点。

假设您有一个名为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");
}

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

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

只需重载Model类的默认构造函数,并传递您可能使用或不使用的任何相关参数。通过这种方式,您可以轻松地为属性提供默认值。下面是一个例子。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Aim.Data.Domain
{
    [MetadataType(typeof(LoginModel))]
    public partial class Login
    {       
        public Login(bool status)
        {
            this.CreatedDate = DateTime.Now;
            this.ModifiedDate = DateTime.Now;
            this.Culture = "EN-US";
            this.IsDefaultPassword = status;
            this.IsActive = status;
            this.LoginLogs = new HashSet<LoginLog>();
            this.LoginLogHistories = new HashSet<LoginLogHistory>();
        }


    }

    public class LoginModel
    {

        [Key]
        [ScaffoldColumn(false)] 
        public int Id { get; set; }
        [Required]
        public string LoginCode { get; set; }
        [Required]
        public string Password { get; set; }
        public string LastPassword { get; set; }     
        public int UserGroupId { get; set; }
        public int FalseAttempt { get; set; }
        public bool IsLocked { get; set; }
        public int CreatedBy { get; set; }       
        public System.DateTime CreatedDate { get; set; }
        public Nullable<int> ModifiedBy { get; set; }      
        public Nullable<System.DateTime> ModifiedDate { get; set; }       
        public string Culture { get; set; }        
        public virtual ICollection<LoginLog> LoginLogs { get; set; }
        public virtual ICollection<LoginLogHistory> LoginLogHistories { get; set; }
    }

}

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()");
}