如何将成员的值限制为< =另一个成员?

时间:2013-10-30 00:22:15

标签: c# asp.net-mvc-4

我在MVC4中使用实体框架,我有以下域类。

我的问题是这样,我如何将SalePrice的值限制为< = Price?我一直在寻找一个合适的属性,可以做到这一点,但没有找到一个。

编辑:

假设一个人在准备提交表格时输入20.00美元的价格,然后他们输入25.00美元的促销价。该计划将禁止此项,因为销售价格不能高于该项目的价格。我想知道是否有[Attribute]可以对SalePrice强制执行此限制。

public class MedicalProduct
{
    [Key]
    public int ID { get; set; }

    [Required]
    [StringLength(50)]
    public string Name { get; set; }

    [Required]
    [DataType(DataType.Currency)]
    public double Price { get; set; }

    // needs to be less than price.
    [Required]
    [DataType(DataType.Currency)]
    public double SalePrice { get; set; }

    // is a foreign key
    public int BrandID { get; set; }

}

2 个答案:

答案 0 :(得分:2)

我会创建一个自定义ValidationAttribute来完全按照您的要求执行操作。该属性需要与之比较的propety名称和ComparisonType。我在下面创建了一个非常快速的示例:

ComparisonAttribute

public enum ComparisonType
{
    LessThan,
    LessThanOrEqual,
    Equal,
    GreaterThanOrEqual,
    GreaterThan,
    NotEqual
}

public sealed class ComparisonAttribute : ValidationAttribute
{

    string PropertyToCompare { get; set; }
    ComparisonType Type { get; set; }

    public ComparisonAttribute(string propertyToCompare, ComparisonType type)
    {
        PropertyToCompare = propertyToCompare;
        Type = type;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (validationContext.ObjectInstance == null || value == null)
            return new ValidationResult("Cannot compare null values");

        PropertyInfo property = validationContext.ObjectType.GetProperty(PropertyToCompare);
        object propertyValue = property.GetValue(validationContext.ObjectInstance, null);

        string errorMessage = "";

        if (value is IComparable)
        {
            int compVal = ((IComparable)value).CompareTo(propertyValue);
            switch (Type)
            {
                case ComparisonType.LessThan:
                    errorMessage = compVal < 0 ? "" : string.Format("{0} is not less than {1}", validationContext.DisplayName, property.Name);
                    break;
                case ComparisonType.LessThanOrEqual:
                    errorMessage = compVal <= 0 ? "" : string.Format("{0} is not less than or equal to {1}", validationContext.DisplayName, property.Name);
                    break;
                case ComparisonType.Equal:
                    errorMessage = compVal == 0 ? "" : string.Format("{0} is not equal to {1}", validationContext.DisplayName, property.Name);
                    break;
                case ComparisonType.GreaterThanOrEqual:
                    errorMessage = compVal >= 0 ? "" : string.Format("{0} is not greater than or equal to {1}", validationContext.DisplayName, property.Name);
                    break;
                case ComparisonType.GreaterThan:
                    errorMessage = compVal > 0 ? "" : string.Format("{0} is not greater than {1}", validationContext.DisplayName, property.Name);
                    break;
                case ComparisonType.NotEqual:
                    errorMessage = compVal != 0 ? "" : string.Format("{0} cannot be equal to {1}", validationContext.DisplayName, property.Name);
                    break;
                default:
                    errorMessage = "";
                    break;
            }
        }

        if (String.IsNullOrEmpty(errorMessage))
            return ValidationResult.Success;

        return new ValidationResult(errorMessage);
    }

}

用法

public class Model
{
    [Comparison("Value2", ComparisonType.LessThanOrEqual)]
    public int Value1 { get; set; }

    public int Value2 { get; set; }

}

答案 1 :(得分:1)

您可以考虑使public double SalePrice { get; set; }成为具有支持字段的功能更全面的属性。然后,在允许Price成为SalePrice之前,您需要测试set的值。这是一个简单的例子:

private double _salePrice;

public double SalePrice
{
    get { return _salePrice; }
    set
    {
        // only set _salePrice if it's less than
        // or equal to Price
        if(value <= Price)
            _salePrice = value;
    }
}

试一试......

[编辑] - 我看到你稍微改了一下这个问题,所以要添加一个,CompareAttribute可以用来相互验证两个属性(不过,我某些这仅限于字符串值 - 将确认)。另外,请看一下这个页面,它有一个看起来很好,很灵活的自定义解决方案,可能适合您:http://forums.asp.net/t/1924941.aspx。 gorra head - 00:43在英国!!