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

也许是DataAnnotations,比如:

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

谢谢你!


当前回答

很简单!只需要注释required即可。

[Required]
public bool MyField { get; set; }

迁移的结果将是:

migrationBuilder.AddColumn<bool>(
name: "MyField",
table: "MyTable",
nullable: false,
defaultValue: false);

如果希望为true,请在更新数据库之前在迁移中将defaultValue更改为true

其他回答

在@SedatKapanoglu评论之后,我添加了我所有的方法,因为他是对的,只是使用流畅的API是行不通的。

1-创建自定义代码生成器和覆盖生成一个ColumnModel。

   public class ExtendedMigrationCodeGenerator : CSharpMigrationCodeGenerator
{

    protected override void Generate(ColumnModel column, IndentedTextWriter writer, bool emitName = false)
    {

        if (column.Annotations.Keys.Contains("Default"))
        {
            var value = Convert.ChangeType(column.Annotations["Default"].NewValue, column.ClrDefaultValue.GetType());
            column.DefaultValue = value;
        }


        base.Generate(column, writer, emitName);
    }

}

2-分配新的代码生成器:

public sealed class Configuration : DbMigrationsConfiguration<Data.Context.EfSqlDbContext>
{
    public Configuration()
    {
        CodeGenerator = new ExtendedMigrationCodeGenerator();
        AutomaticMigrationsEnabled = false;
    }
}

3-使用fluent api创建注释:

public static void Configure(DbModelBuilder builder){    
builder.Entity<Company>().Property(c => c.Status).HasColumnAnnotation("Default", 0);            
}
using System.ComponentModel;

[DefaultValue(true)]

public bool Active { 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()");
}

我发现,只需在实体属性上使用Auto-Property Initializer就足以完成工作。

例如:

public class Thing {
    public bool IsBigThing{ get; set; } = false;
}

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

[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());