0

我想在代码优先方法中为所有十进制字段设置精度。为此

为此创建一个自定义属性:

    [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
    public sealed class DecimalPrecisionAttribute : Attribute
    {
        public DecimalPrecisionAttribute(byte precision, byte scale)
        {
            Precision = precision;
            Scale = scale;

        }

        public byte Precision { get; set; }
        public byte Scale { get; set; }

    }

使用

    [DecimalPrecision(20,10)]
    public Nullable<decimal> DeliveryPrice { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        foreach (Type classType in from t in Assembly.GetAssembly(typeof(DecimalPrecisionAttribute)).GetTypes()
                                       where t.IsClass && t.Namespace == "YOURMODELNAMESPACE"
                                       select t)
         {
             foreach (var propAttr in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute<DecimalPrecisionAttribute>() != null).Select(
                    p => new { prop = p, attr = p.GetCustomAttribute<DecimalPrecisionAttribute>(true) }))
             {

                 var entityConfig = modelBuilder.GetType().GetMethod("Entity").MakeGenericMethod(classType).Invoke(modelBuilder, null);
                 ParameterExpression param = ParameterExpression.Parameter(classType, "c");
                 Expression property = Expression.Property(param, propAttr.prop.Name);
                 LambdaExpression lambdaExpression = Expression.Lambda(property, true,
                                                                          new ParameterExpression[]
                                                                              {param});
                 DecimalPropertyConfiguration decimalConfig;
                 if (propAttr.prop.PropertyType.IsGenericType && propAttr.prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                 {
                     MethodInfo methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[7];
                     decimalConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
                 }
                 else
                 {
                     MethodInfo methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[6];
                     decimalConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
                 }

                 decimalConfig.HasPrecision(propAttr.attr.Precision, propAttr.attr.Scale);
            }
        }
    }

但是会检测到错误,

错误 1“System.Reflection.PropertyInfo”不包含“GetCustomAttribute”的定义,并且找不到接受“System.Reflection.PropertyInfo”类型的第一个参数的扩展方法“GetCustomAttribute”(您是否缺少 using 指令或装配参考?)。

我该如何解决这个问题?

4

0 回答 0