簡體   English   中英

實體框架以編程方式設置模型中的所有十進制精度值

[英]Entity Framework Set All Decimal Precision Values in a model programmatically

這個問題的答案(下面的鏈接)使我想知道我的問題是否可能?

for循環中的Entity Framework Code First Fluent API設置字段屬性

有沒有辦法更動態地做到這一點? 我有多個模型要執行此操作,並且不想在onmodelcreating中為要配置的每個實體類克隆代碼。 可能是空的基類?

在EF6中,您可以使用自定義約定來執行此操作。 不應超過幾行代碼。

在EF5中,您可能必須使用反射來發現您的實體類型,然后按照上面提供的鏈接中的描述進行配置。 這是我想出的代碼(我從上面鏈接帖子中竊取了用於構建用於訪問屬性的表達式的方法):

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    foreach (var contextProperty in typeof(Context).GetProperties())
    {
        if (contextProperty.PropertyType.IsGenericType && 
            contextProperty.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>))
        {
            var entityType = contextProperty.PropertyType.GenericTypeArguments[0];

            foreach(var decimalProperty in entityType.GetProperties().Where(p => p.PropertyType == typeof(decimal)))
            {    
                var configurePropertyMethod = 
                    GetType()
                    .GetMethod("ConfigureProperty", BindingFlags.Static | BindingFlags.NonPublic)
                    .MakeGenericMethod(entityType);
                configurePropertyMethod.Invoke(null, new object[] { modelBuilder, decimalProperty });
            }
        }
    }
}

private static void ConfigureProperty<T>(DbModelBuilder modelBuilder, PropertyInfo propertyInfo) 
    where T : class
{
    var propertyExpression = BuildLambda<T, decimal>(propertyInfo);
    modelBuilder.Entity<T>().Property(propertyExpression).HasPrecision(10, 3);
}

private 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM