Entity Framework Code First fluent API setting field properties in a for loop

前端 未结 2 1467
隐瞒了意图╮
隐瞒了意图╮ 2021-01-24 12:07

I am using Entity Framework Code First to create a database table. My model class has ten decimal fields. Currently I am setting the field property like this in the OnMode

2条回答
  •  攒了一身酷
    2021-01-24 12:30

    This should work for you - using reflection to get all the properties of type decimal in your entity, then building an expression tree for the property access and finally using the property access lambda to set the precision to the desired values.

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        var properties = typeof(Envelopes).GetProperties()
                                          .Where(p => p.PropertyType == typeof(decimal));
    
        foreach (var property in properties)
        {
            var lambda = BuildLambda(property);
            modelBuilder.Entity()
                        .Property(lambda)
                        .HasPrecision(18, 2);
        }
    }
    
    static Expression> BuildLambda(PropertyInfo property)
    {
        var param = Expression.Parameter(typeof(T), "p");
        MemberExpression memberExpression = Expression.Property(param, property);
        var lambda = Expression.Lambda>(memberExpression, param);
        return lambda;
    }
    

提交回复
热议问题