在实体框架code首先流利的API设置字段属性循环字段、流利、实体、框架

2023-09-04 22:34:19 作者:生死皆闲事

我使用实体框架code首先创建一个数据库表。我的模型类有十位十进制领域。目前我设置字段属性像这样的 OnModelCreating 方法:

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 OnModelCreating method:

modelBuilder.Entity<Envelopes>().Property(p => p.cell_1_1).HasPrecision(18, 2);

由于我有十个领域,我想用一个循环这个precision属性设置的,如下面的code:

Since I have ten fields I am thinking of using a for loop to set this precision property such as the following code:

for( int i = 1; i <= 10; i++ ) {
    modelBuilder.Entity<Envelopes>()
                .Property(p => p.Equals("cell_1_"+i ))
                .HasPrecision(18, 2);
}

不过上述code,是给我一个语法错误。

However the above code is giving a me a syntax error.

是否可以这样设置precision价值呢?

Is it possible to set the precision value like this?

推荐答案

这应该为你工作 - 使用反射来获取你的实体类型十进制的所有属性,然后建立一个前pression树属性访问,最后使用属性访问拉姆达设置precision为所需的值。

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<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;
}
 
精彩推荐
图片推荐