ASP.NET Web API OData v4:如何在$metadata中体现decimal精度与小数位数?
在ASP.NET Web API 2.2 + OData v4.0中为decimal类型定义精度与小数位数
当然可以!你完全能在$metadata端点里为decimal属性指定精度和小数位数,只是默认的模型构建逻辑不会自动帮你完成这个配置,得手动做一些调整,我来给你一步步说清楚怎么实现:
方法一:直接在EDM模型构建时手动配置
这是最直接可控的方式,在Startup.cs的模型配置代码里,针对每个decimal属性显式设置精度和小数位:
public void Configuration(IAppBuilder appBuilder) { var config = new HttpConfiguration(); ODataModelBuilder builder = new ODataConventionModelBuilder(); // 注册你的实体集 var pricingEntityType = builder.EntitySet<PricingModel>("Pricing").EntityType; // 为PurchasePrice设置精度18,小数位2 pricingEntityType.Property(p => p.PurchasePrice) .AsDecimal() // 明确指定为Edm.Decimal类型 .HasPrecision(18, 2); // 第一个参数是总精度,第二个是小数位数 // 为SellingPrice设置精度18,小数位4 pricingEntityType.Property(p => p.SellingPrice) .AsDecimal() .HasPrecision(18, 4); // 配置OData路由 config.MapODataServiceRoute("ODataRoute", null, builder.GetEdmModel()); appBuilder.UseWebApi(config); }
方法二:结合DataAnnotations辅助配置
你也可以先在实体类上用ColumnAttribute标记精度和小数位,然后在模型构建时读取这些配置(不过需要额外处理,不如方法一直接):
public class PricingModel { [Column(TypeName = "decimal(18, 2)")] public decimal? PurchasePrice { get; set; } [Column(TypeName = "decimal(18, 4)")] public decimal? SellingPrice { get; set; } }
之后你需要自己解析这个Attribute的TypeName属性,提取精度和小数位,再应用到EDM模型的属性上——这种方式适合已经在EF实体里配置过的场景,但步骤会多一些。
验证配置效果
启动你的项目后,访问/odata/$metadata端点,你应该能看到类似这样的XML片段,说明配置生效了:
<Property Name="PurchasePrice" Type="Edm.Decimal" Precision="18" Scale="2" Nullable="true"/> <Property Name="SellingPrice" Type="Edm.Decimal" Precision="18" Scale="4" Nullable="true"/>
注意事项
- 确保你使用的
Microsoft.AspNet.OData包版本在5.6.0及以上,这个版本才引入了HasPrecision方法来支持精度和小数位的配置。 - 对于可空的decimal属性(比如你的
decimal?类型),OData会自动在metadata里加上Nullable="true",不需要额外配置。
内容的提问来源于stack exchange,提问作者dwikar
相关产品推荐
相关产品推荐

