【发布时间】:2011-01-06 23:44:45
【问题描述】:
我有一个具有以下属性的实体框架生成类:
public DateTime LaunchDate;
public DateTime ExpirationDate;
我需要强制执行 ExpirationDate > LaunchDate。
我正在使用各种帖子中描述的好友类。 我正在将自定义验证属性(在属性上)应用于同一伙伴类中的其他属性,并且这些属性正在工作。
因为我需要比较两个属性,所以我直接在类上使用一个属性 (AttributeTargets.Class)
这是我的自定义验证属性:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class PropertyMustBeGreaterThanAttribute : ValidationAttribute
{
private const string _defaultErrorMessage = "'{0}' must be greater than '{1}'!";
public PropertyMustBeGreaterThanAttribute(string property, string greaterThan)
: base(_defaultErrorMessage)
{
GreaterThan = greaterThan;
Property = property;
}
public string Property { get; private set; }
public string GreaterThan { get; private set; }
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
GreaterThan, Property);
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
IComparable greaterThan = properties.Find(GreaterThan, true /* ignoreCase */).GetValue(value) as IComparable;
IComparable property = properties.Find(Property, true /* ignoreCase */).GetValue(value) as IComparable;
return greaterThan.CompareTo(property) > 0;
}
}
首先我不确定我需要将属性应用到哪个类:
[MetadataType(typeof(PromotionValidation))]
[PropertyMustBeGreaterThanAttribute("RetailPrice")] // apply it here
public partial class Promotion
{
[PropertyMustBeGreaterThanAttribute("ExpirationDate", "LaunchDate")] // or here ???
public class PromotionValidation
{
第二,它不工作,我不知道为什么!!! 我已经尝试为这两个类添加属性。构造函数中的断点被命中(PropertyMustBeGreaterThanAttribute),但永远不会调用 IsValid。
已经把我的头发拉出来了……
谢谢!
【问题讨论】:
标签: asp.net-mvc entity-framework data-annotations