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

也许是DataAnnotations,比如:

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

谢谢你!


当前回答

已经有一段时间了,但给别人留个字条。 我实现了所需要的属性,我装饰我的模型类字段的属性,因为我想要。

[SqlDefaultValue(DefaultValue = "getutcdate()")]
public DateTime CreatedDateUtc { get; set; }

得到了这两篇文章的帮助:

EF在CodePlex Andy Mehalick博客

我做了什么:

定义属性

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class SqlDefaultValueAttribute : Attribute
{
    public string DefaultValue { get; set; }
}

在上下文的“OnModelCreating”中

modelBuilder.Conventions.Add( new AttributeToColumnAnnotationConvention<SqlDefaultValueAttribute, string>("SqlDefaultValue", (p, attributes) => attributes.Single().DefaultValue));

在自定义SqlGenerator中

private void SetAnnotatedColumn(ColumnModel col)
{
    AnnotationValues values;
    if (col.Annotations.TryGetValue("SqlDefaultValue", out values))
    {
         col.DefaultValueSql = (string)values.NewValue;
    }
}

然后在Migration Configuration构造函数中,注册自定义SQL生成器。

SetSqlGenerator("System.Data.SqlClient", new CustomMigrationSqlGenerator());

其他回答

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

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

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

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

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

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

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

public Thingy()
{
  this.Iteration = 1;

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

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

using System.ComponentModel;

[DefaultValue(true)]

public bool Active { get; set; }

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

}