是Validatable对象和MetadataType属性在部分类由框架如MVC使用,例如。
下面是一个使用MetadataType属性的例子:
[MetadataType(typeof(UserMetadata))]
public partial class User
{
private class UserMetadata
{
[DisplayName("User Id")]
public long UserId
{
get;
set;
}
[DisplayName("User Name")]
public string UserName
{
get;
set;
}
}
}
当您使用MVC框架,具有这些属性将被读取自动生成标签字段的宗旨,为相应的显示器的任何模型/编辑。
使用IValidatableObject
public partial class Apple : IValidatableObject // Assume the Apple class has an IList<Color> property called AvailableColors
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
foreach (var color in this.AvailableColors)
{
if (color.Name == "Blue") // No blue apples, ever!
{
yield return new ValidationResult("You cannot have blue apples.");
}
}
}
}
MVC会拿起这个IValidatableObject并确保通过说到它的方式任何苹果的验证步骤将永远不会在蓝色的例子。使用IValidatableObject
编辑
随着日期范围关注的一个例子:
public partial class ObjectWithAStartAndEndDate : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (this.StartDate >= this.EndDate)
{
yield return new ValidationResult("Start and End dates cannot overlap.");
}
}
}
那么主要确保实体是一件有效的事情? – GraemeMiller
任何类型的业务逻辑,真的。如果您有另一个不同类型的属性被设置并且不需要其他属性时需要一个属性,则可以通过在部分类中实现“ghost方法”来完成此操作。 –
我想我正在使用AutoMapper来制作ViewModels并且它们有显示名称。不过,我想我需要在ViewModel和Entity上强制执行所需的等。 – GraemeMiller