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

前端 未结 2 1448
隐瞒了意图╮
隐瞒了意图╮ 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

    model creation with some reflection

    var entityTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.IsClass && t.Namespace == "Namespace.Enitites");
    foreach (var type in entityTypes)
    {
        foreach (var property in type.GetProperties().Where(p => p.PropertyType == typeof(decimal)))
        {
            var entityConfig = modelBuilder.GetType().GetMethod("Entity").MakeGenericMethod(type).Invoke(modelBuilder, null);
            var param = Expression.Parameter(type, "c");
            var lambdaExpression = Expression.Lambda(Expression.Property(param, property), true, new[] { param });
    
            var items = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property" && p.ReturnType == typeof(DecimalPropertyConfiguration)).ToArray();
            if (items.Length <= 0)
                continue;
    
            MethodInfo methodInfo;
            if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                methodInfo = items[1];
            else
                methodInfo = items[0];
    
            var decimalConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
            if (decimalConfig != null)
                decimalConfig.HasPrecision(19, 4);
        }
    }
    

    or

    modelBuilder.Conventions.Remove();
    modelBuilder.Conventions.Add(new DecimalPropertyConvention(19, 4));
    

提交回复
热议问题