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

也许是DataAnnotations,比如:

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

谢谢你!


当前回答

即使在。net Core 1.0中,当你使用代码优先的方法时,也可以设置默认值。请参阅下面的代码片段。

using System.ComponentModel;
[DefaultValue(true)]
public bool Active { get; set; }

阅读:微软官方文档

其他回答

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

只需重载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; }
    }

}

在MSSQL Server中为表中的列设置默认值,并在类代码中添加属性,如下所示:

[DatabaseGenerated (DatabaseGeneratedOption断层扫描)。]

对于相同的性质。

嗯…我先做DB,在这种情况下,这实际上要简单得多。EF6对吧?只需打开你的模型,右键单击你想要设置默认值的列,选择属性,你会看到一个“DefaultValue”字段。填好并保存。它将为您设置代码。

你的里程数可能会在代码上有所不同,但我没有使用过这种方法。

许多其他解决方案的问题是,虽然它们最初可能有效,但一旦您重新构建模型,它就会抛出您插入到机器生成文件中的任何自定义代码。

这个方法通过在edmx文件中添加一个额外的属性来工作:

<EntityType Name="Thingy">
  <Property Name="Iteration" Type="Int32" Nullable="false" **DefaultValue="1"** />

通过在构造函数中添加必要的代码:

public Thingy()
{
  this.Iteration = 1;

在。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'.