我正在使用Entity Framework Code First来创建数据库表。我的模型类有十个十进制字段。目前我在OnModelCreating
方法中设置了这样的字段属性:
modelBuilder.Entity<Envelopes>().Property(p => p.cell_1_1).HasPrecision(18, 2);
由于我有十个字段,我正在考虑使用for
循环来设置此精度属性,例如以下代码:
for( int i = 1; i <= 10; i++ ) {
modelBuilder.Entity<Envelopes>()
.Property(p => p.Equals("cell_1_"+i ))
.HasPrecision(18, 2);
}
但是上面的代码给了我一个语法错误。
是否可以像这样设置精度值?
答案 0 :(得分:4)
这应该对你有用 - 使用反射来获取实体中类型decimal
的所有属性,然后为属性访问构建表达式树,最后使用属性访问lambda将精度设置为所需的值。
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<Envelopes, decimal>(property);
modelBuilder.Entity<Envelopes>()
.Property(lambda)
.HasPrecision(18, 2);
}
}
static Expression<Func<T, U>> BuildLambda<T,U>(PropertyInfo property)
{
var param = Expression.Parameter(typeof(T), "p");
MemberExpression memberExpression = Expression.Property(param, property);
var lambda = Expression.Lambda<Func<T, U>>(memberExpression, param);
return lambda;
}
答案 1 :(得分:0)
使用一些反射创建模型
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);
}
}
或
modelBuilder.Conventions.Remove<DecimalPropertyConvention>();
modelBuilder.Conventions.Add(new DecimalPropertyConvention(19, 4));