【问题标题】:Conditionally required attribute for nested object嵌套对象的条件必需属性
【发布时间】:2021-08-14 04:57:05
【问题描述】:

我必须根据特定条件验证该字段。我可以验证位于类中的属性。但我无法验证嵌套对象。请参考下面我的代码 sn-p。

如果 Student.Id 为 10,我需要设置 POBox 属性 Country。

public class Student
{
    public int Id { get; set; }

    public string Name { get; set; }

    [RequiredIf("Id", 10)]
    public int Class { get; set; }

    public Country Country { get; set; }
}

public class Country
{

    **//// I need to validate this property based on the value property located in student class.**
    /// <summary>
    /// PO Box number is required if student id is 10
    /// </summary>
    [RequiredIf("Student.Id", 10)]
    public string POBox { get; set; }
    // POBox is required in Ethiopia
    public string Name { get; set; }

    public string State { get; set; }
    // State is required in US
    public string destination { get; set; }
}

【问题讨论】:

    标签: c# .net-core webapi


    【解决方案1】:

    但是国家不知道学生,所以即使您的自定义属性代码可以遵循 Student.Id 的点路径,国家也不会链接到链接到它的学生。并不是每个学生国家链接的自动魔法全局注册表会介入并进入“哦,这是加拿大国家,学生约翰对象链接到它,所以这个国家的学生是约翰”..

    正如您所拥有的那样,添加一个属性 Student 到 Country 可能是最简单的,当您创建一个国家(因此国家和学生在两个方向上链接)和另一个属性 StudentId 时,您将其链接到学生中在 Student 属性中链接的实例.. 然后,您可以在该国家/地区的属性“StudentId”上使用RequiredIf

    所有这一切都假设学生与国家的关系是 1:1。如果您的国家/地区实例是单一的,并且许多学生与之相关,则您需要重新考虑策略

    【讨论】:

    • 其实我只是提供了样例代码问专家是否可以在嵌套对象属性上添加requiredif注解。但我的具体情况不同。
    • 你有我的评论。当您的问题是另一个问题时,总是有风险提出一个问题;您可能无法将收到的建议翻译成适用于实际问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 2018-03-06
    • 1970-01-01
    • 2015-10-25
    • 2016-07-06
    • 1970-01-01
    • 2016-11-11
    相关资源
    最近更新 更多