Search code examples
c#attributesentity-framework-corecustom-data-attribute

What is the Entity Framework Core attribute equivalent to modelBuilder's HasDefaultValueSql?


I want to use annotations for setting the default value for my properties in Entity Framework Core. The issue is that the database is not setting the default values so the value is not being passed down to the database layer.

I want to do something similar to modelBuilder's HasDefaultValueSql:

[DefaultValue("400")]
public int LengthInMeters {get; set;}

How do you convert the below code to attributes?

modelBuilder.Entity<Patient>().Property(c => c.LengthInMeters).HasDefaultValueSql("400");

Using default values by themselves doesn't work. I want to use attributes alone without having to mess with the migrations.

Problems: I've tried other methods with EF but Entity Framework Core doesn't have some items. Such as modelBuilder.Conventions nor AttributeToColumnAnnotationConvention nor CSharpMigrationCodeGenerator nor modelBuilder.Properties()


Solution

  • This is what I ended up doing, if someone has a cleaner not as intensive way of implementation let me know.

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        foreach (var entityType in modelBuilder.Model.GetEntityTypes())
        {
            foreach (var property in entityType.GetProperties())
            {
                var memberInfo = property.PropertyInfo ?? (MemberInfo)property.FieldInfo;
                if (memberInfo == null) continue;
                var defaultValue = Attribute.GetCustomAttribute(memberInfo, typeof(DefaultValueAttribute)) as DefaultValueAttribute;
                if (defaultValue == null) continue;                   
                property.SqlServer().DefaultValue = defaultValue.Value;
            }
        }
    }       
    

    I can set the default value in the database using the default value attribute

    [DefaultValue("400")]
    public int LengthInMeters {get; set;}