利用DataAnnotations验证实体(类)的属性

.NET 4 和Silverlight 中可以使用以下方法:

public static void Validate(this Entity entity)

{

    // prepare the result

    var validationResults = new List<ValidationResult>();

    // create a validation context

    var validationContext = new ValidationContext(entity, null, null);

    // validate

    Validator.TryValidateObject(entity, validationContext, validationResults);

    // reset the validation errors of the entity

    entity.ValidationErrors.Clear();

    foreach (var error in validationResults)

        entity.ValidationErrors.Add(error);

}

.NET 3.5中的方法:

	public static class EntityValidator

	{

		public static IEnumerable<ErrorField> GetErrors(object instance)

		{

			var t = instance.GetType();

			var typeDescriptor = new AssociatedMetadataTypeTypeDescriptionProvider(t).GetTypeDescriptor(t);



			return from prop in typeDescriptor.GetProperties().Cast<PropertyDescriptor>()

					 from attribute in prop.Attributes.OfType<ValidationAttribute>()

					 where !attribute.IsValid(prop.GetValue(instance))

					 select new ErrorField(prop.Name, attribute.FormatErrorMessage(string.Empty));

		}	

	}



	[Serializable]

	public class ErrorField

	{

		public string ID { get; set; }

		

		public string Msg { get; set; }



		public ErrorField(string id, string msg)

		{

			this.ID = id;

			this.Msg = msg;

		}





	}

你可能感兴趣的:(Annotations)