我可以使用数据注释来指定具有必需属性的可选对象属性吗?

时间:2019-01-28 20:06:55

标签: data-annotations

我有一个简单的成员注册数据模型,其中包含一些必需的属性和一些可选的属性。 BillToAddress属性是可选的。

public class MemberRegistration
{
    [Required(ErrorMessage = "First Name is required.")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Last Name is required.")]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Email Address is required.")]
    public string EmailAddress { get; set; }

    public string PhoneNumber { get; set; }

    [Required(ErrorMessage = "Password is required.")]
    [MinLength(7, ErrorMessage = "Password must be at least 7 characters.")]
    public string Password { get; set; }

    private Address m_BillToAddress;
    public Address BillToAddress
    {
        get
        {
            if (m_BillToAddress == null)
            {
                m_BillToAddress = new Address();
            }
            return m_BillToAddress;
        }
    }
}

如果用户输入可选的帐单地址,我希望输入街道,城市,国家和邮政编码。因此,我定义了地址数据模型,并根据需要标记了这些属性。

public class Address
{
    [Required(ErrorMessage = "Street Line 1 is required.")]
    public string Street1 { get; set; }

    public string Street2 { get; set; }

    public string Street3 { get; set; }

    public string Street4 { get; set; }

    public string Street5 { get; set; }

    [Required(ErrorMessage = "City is required.")]
    public string City { get; set; }

    [Required(ErrorMessage = "State or Province is required.")]
    public string StateOrProvince { get; set; }

    [Required(ErrorMessage = "Country is required.")]
    public string Country { get; set; }

    [Required(ErrorMessage = "Postal Code is required.")]
    public string PostalCode { get; set; }
}

但是,当我不提供解决方案时,模型验证就会失败。如何注释我的模型,以便要处理的帐单是可选的,但是(如果提供),则必须包括街道,城市,国家/地区和邮政编码?

1 个答案:

答案 0 :(得分:0)

问题出在MemberRegistration类中。因为BillToAddress属性getter总是返回一个新的空Address模型,所以BillToAddress永远不会为null,并且总是正确触发Address类验证。我将BillToAddress更改为一个简单的自动实现的属性:

O(n)

现在,如果我发布不带BillToAddress的MemberRegistion,则它将通过验证,因为BillToAddress是可选属性。