c# - 空数组的默认值数据注释

标签 c# .net

我正在创建一个 .NET Core Web API 并想调用一个提交客户订单的端点。客户 ID 作为路由参数出现。在请求正文中,可以发送一组对象。每个对象都包含产品 ID 及其数量。但是这个字段是可选的,空订单也是可能的(产品可以稍后添加)。

所以我从这个 DTO 开始

public class CreateCustomerOrderByIdDto
{
    [FromRoute]
    public uint Id { get; set; }

    [FromBody]
    public OrderPosition[] OrderPositions { get; set; }
}

public class OrderPosition
{
    [Range(1, uint.MaxValue)]
    public uint ProductId { get; set; }

    [Range(1, uint.MaxValue)]
    public uint Amount { get; set; }
}

此请求 DTO 应使 OrderPositions字段可选,但在添加项目时,该项目需要两个属性。我想为 OrderPositions 设置一个默认值如果丢失所以我认为这个数据注释可以做到
[DefaultValue(new OrderPosition[0])]
不幸的是我收到此错误消息

An attribute argument must be a constant expression, 'typeof()' expression or array creation expression of an attribute parameter type



那么如何将该字段标记为可选并设置默认值呢?

当不传递任何订单位置时,数组将转换为空数组,这样我就可以避免空检查并使用从未运行的循环

最佳答案

也许你可以使用 List<OrderPosition>而不是数组。然后在构造函数中将其初始化为空列表

public class CreateCustomerOrderByIdDto
{
    public CreateCustomerOrderByIdDto()
    {
        this.OrderPositions = new List<OrderPosition>();
    }
    [FromRoute]
    public uint Id { get; set; }

    [FromBody]
    public List<OrderPosition> OrderPositions { get; set; }
}

public class OrderPosition
{
    [Range(1, uint.MaxValue)]
    public uint ProductId { get; set; }

    [Range(1, uint.MaxValue)]
    public uint Amount { get; set; }
}

关于c# - 空数组的默认值数据注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62204066/

相关文章:

c# - 字符串未被识别为使用 C# 的有效日期时间

c# - OpCodes.Castclass。有必要吗?

C# - IDataReader 到使用泛型的对象映射

c# - 循环访问 SSIS 中的表时刷新元数据

.net - 异常处理应用程序 block 和异常处理之间有什么区别

java - 通过 Nexmo API 将回调 URL 分配给短信号码

.net - 将 .NET 项目编译为独立 native 二进制文件的可用工具有哪些?

.NET - 多数据库支持策略

c# - 强制转换为无效枚举值 Enum.ToObject,不会引发异常,将 Enum 设置为 int

c# - Entity Framework 无法更改关系,因为一个或多个外键属性不可为空