【问题标题】:Decimal precision and scale in EF Code FirstEF Code First 中的小数精度和小数位数
【发布时间】:2011-03-31 02:22:54
【问题描述】:

我正在试验这种代码优先的方法,但我现在发现 System.Decimal 类型的属性被映射到 decimal(18, 0) 类型的 sql 列。

如何设置数据库列的精度?

【问题讨论】:

  • 一种方法是为您的小数属性使用[Column(TypeName = "decimal(18,4)")] 属性
  • [Column(TypeName = "decimal(18,4)")] 效果很好!!!

标签: c# .net entity-framework ef-code-first decimal


【解决方案1】:

Dave Van den Eynde 的回答现在已经过时了。有 2 个重要变化,从 EF 4.1 开始,ModelBuilder 类现在是 DbModelBuilder,现在有一个 DecimalPropertyConfiguration.HasPrecision 方法,其签名为:

public DecimalPropertyConfiguration HasPrecision(
byte precision,
byte scale )

其中精度是 db 将存储的总位数,无论小数点落在哪里,而 scale 是它将存储的小数位数。

因此不需要遍历属性,但可以从

public class EFDbContext : DbContext
{
   protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
   {
       modelBuilder.Entity<Class>().Property(object => object.property).HasPrecision(12, 10);

       base.OnModelCreating(modelBuilder);
   }
}

【讨论】:

  • 我注意到你从来没有打电话给base.OnModelCreating(modelBuilder);。这是故意的还是只是在线而不是在 IDE 中输入代码的受害者?
  • @BenSwayne 感谢现场,这是我的遗漏,不是故意的。我将编辑答案。
  • HasPrecision(precision, scale) 的 2 个参数没有得到很好的记录。精度是它将存储的总位数,无论小数点在哪里。 scale 是它将存储的小数位数。
  • 是否有 EF 配置可以在一个地方为所有实体的所有十进制属性设置它?我们通常使用 (19,4) 。最好将其自动应用于所有小数属性,因此我们不能忘记设置属性精度并错过计算中的预期精度。
  • 在 Property(object =&gt; object.property) 中,将 object 更改为 x 以使其编译
【解决方案2】:

如果您想在 EF6 中为所有 decimals 设置精度,您可以替换 DbModelBuilder 中使用的默认 DecimalPropertyConvention 约定:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<DecimalPropertyConvention>();
    modelBuilder.Conventions.Add(new DecimalPropertyConvention(38, 18));
}

EF6 中的默认DecimalPropertyConvention 将decimal 属性映射到decimal(18,2) 列。

如果您只希望单个属性具有指定的精度,那么您可以在DbModelBuilder 上设置实体属性的精度:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<MyEntity>().Property(e => e.Value).HasPrecision(38, 18);
}

或者,为指定精度的实体添加EntityTypeConfiguration&lt;&gt;:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new MyEntityConfiguration());
}

internal class MyEntityConfiguration : EntityTypeConfiguration<MyEntity>
{
    internal MyEntityConfiguration()
    {
        this.Property(e => e.Value).HasPrecision(38, 18);
    }
}

【讨论】:

  • 我最喜欢的解决方案。使用 CodeFirst 和迁移时完美运行:EF 在所有使用“十进制”的类中查找所有属性,并为这些属性生成迁移。太好了!
【解决方案3】:

我很高兴为此创建了一个自定义属性:

[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(System.Data.Entity.ModelConfiguration.ModelBuilder 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);
        }
    }
}

第一部分是获取模型中的所有类(我的自定义属性是在该程序集中定义的,所以我用它来获取模型的程序集)

第二个 foreach 使用自定义属性获取该类中的所有属性,以及属性本身,因此我可以获得精度和比例数据

之后我必须打电话

modelBuilder.Entity<MODEL_CLASS>().Property(c=> c.PROPERTY_NAME).HasPrecision(PRECISION,SCALE);

所以我通过反射调用 modelBuilder.Entity() 并将其存储在 entityConfig 变量中 然后我构建“c => c.PROPERTY_NAME” lambda 表达式

之后,如果小数可以为空,我调用

Property(Expression<Func<TStructuralType, decimal?>> propertyExpression) 

方法(我通过数组中的位置调用它,我知道这并不理想,任何帮助将不胜感激)

如果它不可为空,我会调用

Property(Expression<Func<TStructuralType, decimal>> propertyExpression)

方法。

拥有 DecimalPropertyConfiguration 我调用 HasPrecision 方法。

【讨论】:

  • 谢谢。它使我免于生成数千个 lambda 表达式。
  • 这很好用,而且超级干净!对于 EF 5,我将 System.Data.Entity.ModelConfiguration.ModelBuilder 更改为 System.Data.Entity.DbModelBuilder
  • 我使用MethodInfo methodInfo = entityConfig.GetType().GetMethod("Property", new[] { lambdaExpression.GetType() }); 来获得正确的重载。到目前为止似乎有效。
  • 我已将其打包到一个库中,并使其更容易从 DbContext 调用:github.com/richardlawley/EntityFrameworkAttributeConfig(也可通过 nuget 获得)
  • 这有一个巨大的错误: MethodInfo methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[7];这里的 7 是硬编码的,并假定该类型将为可为空的十进制。但是由于某种原因,我的 .net 决定调换顺序,现在 datetime 在该列表中的索引 7 处,这让整个事情都崩溃了。
【解决方案4】:

使用来自 KinSlayerUY 的 DecimalPrecisonAttribute,在 EF6 中,您可以创建一个约定来处理具有该属性的各个属性(而不是像在 this answer 中设置 DecimalPropertyConvention 那样会影响所有十进制属性)。

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

public class DecimalPrecisionAttributeConvention
    : PrimitivePropertyAttributeConfigurationConvention<DecimalPrecisionAttribute>
{
    public override void Apply(ConventionPrimitivePropertyConfiguration configuration, DecimalPrecisionAttribute attribute)
    {
        if (attribute.Precision < 1 || attribute.Precision > 38)
        {
            throw new InvalidOperationException("Precision must be between 1 and 38.");
        }

        if (attribute.Scale > attribute.Precision)
        {
            throw new InvalidOperationException("Scale must be between 0 and the Precision value.");
        }

        configuration.HasPrecision(attribute.Precision, attribute.Scale);
    }
}

然后在你的DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Add(new DecimalPrecisionAttributeConvention());
}

【讨论】:

  • @MichaelEdenfield 实际上不,EF6 中没有这些。因此,为什么我添加了两个答案,这个和您提到的另一个。这是一个可以放在单个小数属性上的属性,而不是影响模型中的所有小数属性。
  • 我的错,没注意到你两个都写了:\
  • 如果你要对Precision进行边界检查,那么我建议将上限设置为28(所以&gt; 28在你的情况下)。根据 MSDN 文档,System.Decimal 最多只能表示 28-29 位精度 (msdn.microsoft.com/en-us/library/364x0z75.aspx)。此外,该属性将Scale 声明为byte,这意味着您的前提条件attribute.Scale &lt; 0 是不必要的。
  • @kjbartel 确实有些数据库提供者支持大于 28 的精度;但是,根据 MSDN,System.Decimal 没有。因此,将上限前提条件设置为大于 28 的值是没有意义的; System.Decimal 显然不能代表那么大的数字。此外,请注意,此属性对 SQL Server 以外的数据提供程序很有用。例如,PostgreSQL 的 numeric 类型最多支持 131072 位的精度。
  • @NathanAldenSr 就像我说的,数据库使用定点十进制 (msdn) 而 System.Decimal 是浮点。它们完全不同。例如,拥有decimal(38,9) 列将很高兴持有System.Decimal.MaxValue,但decimal(28,9) 列不会。没有理由将精度限制为仅 28。
【解决方案5】:

显然,您可以重写 DbContext.OnModelCreating() 方法并像这样配置精度:

protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Product>().Property(product => product.Price).Precision = 10;
    modelBuilder.Entity<Product>().Property(product => product.Price).Scale = 2;
}

但是,当您必须处理所有与价格相关的属性时,这是非常乏味的代码,所以我想出了这个:

    protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
    {
        var properties = new[]
        {
            modelBuilder.Entity<Product>().Property(product => product.Price),
            modelBuilder.Entity<Order>().Property(order => order.OrderTotal),
            modelBuilder.Entity<OrderDetail>().Property(detail => detail.Total),
            modelBuilder.Entity<Option>().Property(option => option.Price)
        };

        properties.ToList().ForEach(property =>
        {
            property.Precision = 10;
            property.Scale = 2;
        });

        base.OnModelCreating(modelBuilder);
    }

最好在重写方法时调用基方法,即使基实现什么也不做。

更新:This article 也很有帮助。

【讨论】:

  • 谢谢,这为我指明了正确的方向。在 CTP5 中,语法已更改为允许在同一语句中添加 Precision 和 Scale:modelBuilder.Entity().Property(product => product.Price).HasPrecision(6, 2);
  • 不过,如果您可以为 all 小数设置某种“默认”不是很好吗?
  • 我认为没有必要打电话给base.OnModelCreating(modelBuilder);。来自 VS 中的 DbContext 元数据:The default implementation of this method does nothing, but it can be overridden in a derived class such that the model can be further configured before it is locked down.
  • @Matt:这很好,但作为一个实现者我不应该关心这个并且总是调用基础。
  • @Dave 和@Matt:有一条评论说调用 base 是“重要的”。这是一种很好的做法,但是当 EF 源有一个空 implementation 时,声称它很重要是一种误导。这让人们想知道基地的作用。我很好奇什么是重要的,我反编译到 ef5.0 来检查。那里空无一物。所以只是一个好习惯。
【解决方案6】:
[Column(TypeName = "decimal(18,2)")]

这将适用于 EF Core 代码优先迁移,如 here 所述。

【讨论】:

  • 如果你只是把这个添加到你的模型中,你可以得到The store type 'decimal(18,2)' could not be found in the SqlServer provider manifest
  • @Savage 看起来是您的数据库提供商或数据库版本的问题
  • @Elnoor Savage 是正确的,这将在 EF Migrations 6.x 中引发错误。旧的非核心版本不支持通过 Column 属性指定精度/比例,如果您使用 DataType 属性,则不执行任何操作(默认为 18,2)。要通过 EF 6.x 中的 Attribute 使其工作,您需要实现自己的 ModelBuilder 扩展。
  • @ChrisMoschini,我更改了提到 EF Core 的答案。谢谢
【解决方案7】:

Entity Framework Ver 6 (Alpha, rc1) 有一个叫做Custom Conventions的东西。设置小数精度:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Properties<decimal>().Configure(config => config.HasPrecision(18, 4));
}

参考:

【讨论】:

    【解决方案8】:

    此代码行可能是完成相同操作的更简单方法:

     public class ProductConfiguration : EntityTypeConfiguration<Product>
        {
            public ProductConfiguration()
            {
                this.Property(m => m.Price).HasPrecision(10, 2);
            }
        }
    

    【讨论】:

      【解决方案9】:

      - FOR EF CORE - 使用 System.ComponentModel.DataAnnotations;

      使用[Column(TypeName= "decimal(precision, scale)")]

      精度 = 使用的字符总数

      比例 = 点后的总数。 (容易混淆)

      示例:

      public class Blog
      {
          public int BlogId { get; set; }
          [Column(TypeName = "varchar(200)")]
          public string Url { get; set; }
          [Column(TypeName = "decimal(5, 2)")]
          public decimal Rating { get; set; }
      }
      

      更多详情:https://docs.microsoft.com/en-us/ef/core/modeling/relational/data-types

      【讨论】:

        【解决方案10】:

        从 .NET EF Core 6 开始,您可以使用 Precision 属性。

            [Precision(18, 2)]
            public decimal Price { get; set; }
        

        确保您需要安装 EF Core 6 并遵循using 行

        using Microsoft.EntityFrameworkCore;
        

        【讨论】:

          【解决方案11】:

          您始终可以通过 OnModelCreating 函数的 Context 类中的约定告诉 EF 执行此操作,如下所示:

          protected override void OnModelCreating(DbModelBuilder modelBuilder)
          {
              // <... other configurations ...>
              // modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
              // modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
              // modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
          
              // Configure Decimal to always have a precision of 18 and a scale of 4
              modelBuilder.Conventions.Remove<DecimalPropertyConvention>();
              modelBuilder.Conventions.Add(new DecimalPropertyConvention(18, 4));
          
              base.OnModelCreating(modelBuilder);
          }
          

          这仅适用于 Code First EF 仅供参考,并适用于映射到 db 的所有十进制类型。

          【讨论】:

          • 直到Remove&lt;DecimalPropertyConvention&gt;(); 出现在Add(new DecimalPropertyConvention(18, 4)); 之前才起作用。我认为不只是自动覆盖很奇怪。
          【解决方案12】:

          在 EF6 中

          modelBuilder.Properties()
              .Where(x => x.GetCustomAttributes(false).OfType<DecimalPrecisionAttribute>().Any())
              .Configure(c => {
                  var attr = (DecimalPrecisionAttribute)c.ClrPropertyInfo.GetCustomAttributes(typeof (DecimalPrecisionAttribute), true).FirstOrDefault();
          
                  c.HasPrecision(attr.Precision, attr.Scale);
              });
          

          【讨论】:

          • 此答案似乎是对定义属性的另一个答案的升级,您应该将其编辑到该答案中
          【解决方案13】:

          使用

          System.ComponentModel.DataAnnotations;
          

          您可以简单地将该属性放入您的模型中:

          [DataType("decimal(18,5)")]
          

          【讨论】:

          • 这是可读性和简单性的最简单的实现。恕我直言
          • 根据msdn.microsoft.com/en-us/library/jj591583(v=vs.113).aspx,这个答案实际上是不正确的。 “不要将 Column 的 TypeName 属性与 DataType DataAnnotation 混淆。DataType 是用于 UI 的注释,被 Code First 忽略。”
          • @ransems 我也是这么认为的,直到我刚刚测试它并且如上所述,这对 CodeFirst 不起作用并且不会迁移到数据库
          【解决方案14】:

          您可以在 MSDN - 实体数据模型方面找到更多信息。 http://msdn.microsoft.com/en-us/library/ee382834.aspx 完全推荐。

          【讨论】:

          • 这很好,但这与 Code-First 有什么关系?
          • 它很有用,但我仍然不能为 Decimal 指定 [Precision] 属性。所以我使用了@KinSlayerUY提供的解决方案。
          【解决方案15】:

          EntityFrameworkCore 3.1.3 的实际情况:

          OnModelCreating 中的一些解决方案:

          var fixDecimalDatas = new List<Tuple<Type, Type, string>>();
          foreach (var entityType in builder.Model.GetEntityTypes())
          {
              foreach (var property in entityType.GetProperties())
              {
                  if (Type.GetTypeCode(property.ClrType) == TypeCode.Decimal)
                  {
                      fixDecimalDatas.Add(new Tuple<Type, Type, string>(entityType.ClrType, property.ClrType, property.GetColumnName()));
                  }
              }
          }
          
          foreach (var item in fixDecimalDatas)
          {
              builder.Entity(item.Item1).Property(item.Item2, item.Item3).HasColumnType("decimal(18,4)");
          }
          
          //custom decimal nullable:
          builder.Entity<SomePerfectEntity>().Property(x => x.IsBeautiful).HasColumnType("decimal(18,4)");
          

          【讨论】:

            【解决方案16】:

            KinSlayerUY 的自定义属性对我来说效果很好,但我遇到了 ComplexTypes 的问题。它们被映射为属性代码中的实体,因此无法映射为 ComplexType。

            因此我扩展了代码以允许这样做:

            public static void OnModelCreating(DbModelBuilder modelBuilder)
                {
                    foreach (Type classType in from t in Assembly.GetAssembly(typeof(DecimalPrecisionAttribute)).GetTypes()
                                               where t.IsClass && t.Namespace == "FA.f1rstval.Data"
                                               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) }))
                        {
            
                            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;
                            int MethodNum;
                            if (propAttr.prop.PropertyType.IsGenericType && propAttr.prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                            {
                                MethodNum = 7;
                            }
                            else
                            {
                                MethodNum = 6;
                            }
            
                            //check if complextype
                            if (classType.GetCustomAttribute<ComplexTypeAttribute>() != null)
                            {
                                var complexConfig = modelBuilder.GetType().GetMethod("ComplexType").MakeGenericMethod(classType).Invoke(modelBuilder, null);
                                MethodInfo methodInfo = complexConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[MethodNum];
                                decimalConfig = methodInfo.Invoke(complexConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
                            }
                            else
                            {
                                var entityConfig = modelBuilder.GetType().GetMethod("Entity").MakeGenericMethod(classType).Invoke(modelBuilder, null);
                                MethodInfo methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[MethodNum];
                                decimalConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
                            }
            
                            decimalConfig.HasPrecision(propAttr.attr.Precision, propAttr.attr.Scale);
                        }
                    }
                }
            

            【讨论】:

              【解决方案17】:

              @Mark007,我已将类型选择标准更改为使用 DbContext 的 DbSet 属性。我认为这更安全,因为有时您在给定名称空间中的类不应该是模型定义的一部分,或者它们是但不是实体。或者您的实体可以驻留在单独的命名空间或单独的程序集中,并被拉到一个上下文中。

              另外,虽然不太可能,但我认为依赖方法定义的顺序是不安全的,所以最好通过参数列表将它们拉出来。 (.GetTypeMethods() 是我为使用新的 TypeInfo 范式而构建的扩展方法,可以在查找方法时展平类层次结构。

              请注意 OnModelCreating 代表此方法:

                  private void OnModelCreatingSetDecimalPrecisionFromAttribute(DbModelBuilder modelBuilder)
                  {
                      foreach (var iSetProp in this.GetType().GetTypeProperties(true))
                      {
                          if (iSetProp.PropertyType.IsGenericType
                                  && (iSetProp.PropertyType.GetGenericTypeDefinition() == typeof(IDbSet<>) || iSetProp.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>)))
                          {
                              var entityType = iSetProp.PropertyType.GetGenericArguments()[0];
              
                              foreach (var propAttr in entityType
                                                      .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                                                      .Select(p => new { prop = p, attr = p.GetCustomAttribute<DecimalPrecisionAttribute>(true) })
                                                      .Where(propAttr => propAttr.attr != null))
                              {
                                  var entityTypeConfigMethod = modelBuilder.GetType().GetTypeInfo().DeclaredMethods.First(m => m.Name == "Entity");
                                  var entityTypeConfig = entityTypeConfigMethod.MakeGenericMethod(entityType).Invoke(modelBuilder, null);
              
                                  var param = ParameterExpression.Parameter(entityType, "c");
                                  var lambdaExpression = Expression.Lambda(Expression.Property(param, propAttr.prop.Name), true, new ParameterExpression[] { param });
              
                                  var propertyConfigMethod =
                                      entityTypeConfig.GetType()
                                          .GetTypeMethods(true, false)
                                          .First(m =>
                                          {
                                              if (m.Name != "Property")
                                                  return false;
              
                                              var methodParams = m.GetParameters();
              
                                              return methodParams.Length == 1 && methodParams[0].ParameterType == lambdaExpression.GetType();
                                          }
                                          );
              
                                  var decimalConfig = propertyConfigMethod.Invoke(entityTypeConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
              
                                  decimalConfig.HasPrecision(propAttr.attr.Precision, propAttr.attr.Scale);
                              }
                          }
                      }
                  }
              
              
              
                  public static IEnumerable<MethodInfo> GetTypeMethods(this Type typeToQuery, bool flattenHierarchy, bool? staticMembers)
                  {
                      var typeInfo = typeToQuery.GetTypeInfo();
              
                      foreach (var iField in typeInfo.DeclaredMethods.Where(fi => staticMembers == null || fi.IsStatic == staticMembers))
                          yield return iField;
              
                      //this bit is just for StaticFields so we pass flag to flattenHierarchy and for the purpose of recursion, restrictStatic = false
                      if (flattenHierarchy == true)
                      {
                          var baseType = typeInfo.BaseType;
              
                          if ((baseType != null) && (baseType != typeof(object)))
                          {
                              foreach (var iField in baseType.GetTypeMethods(true, staticMembers))
                                  yield return iField;
                          }
                      }
                  }
              

              【讨论】:

              • 我刚刚意识到我没有通过这种方法处理 ComplexTypes。稍后会修改。
              • 然而,Brian 提出的解决方案简单、优雅且有效。我不会对性能做出任何明确的陈述,但使用已经反映的 PropertyInfo 而不是追捕你的应该会在非常大的模型(大约 200 及以上)上产生更好的性能。
              猜你喜欢
              • 2013-07-17
              • 2014-09-14
              • 2014-02-07
              • 1970-01-01
              • 2020-03-18
              • 1970-01-01
              • 2012-08-19
              • 1970-01-01
              相关资源
              最近更新 更多