在实体框架code首先流利的API设置字段属性循环 [英] Entity Framework Code First fluent API setting field properties in a for loop
问题描述
我使用实体框架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;
}
这篇关于在实体框架code首先流利的API设置字段属性循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!