DataAnnotations Cheat Sheet v1.0
Name: AssociationAttribute
Description: Specifies that an entity member represents a data relationship, such as a foreign key relationship.
Usage: [Association(Name, OtherKey, ThisKey)]
Example:
[Table(Name = "Customers")]
public partial class Customer
{
[Column(IsPrimaryKey = true)]
public string CustomerID;
// ...
private EntitySet<Order> _Orders;
[Association(Storage = "_Orders", OtherKey = "CustomerID")]
public EntitySet<Order> Orders
{
get { return this._Orders; }
set { this._Orders.Assign(value); }
}
}
Name: BindableTypeAttribute
Description: Specifies whether a type is typically used for binding.
Usage: [BindableType(IsBindable = bool)]
Example:
[BindableType(IsBindable = false)]
public enum EntityState
{
Detached = 1,
Unchanged = 2,
Added = 4,
Deleted = 8,
Modified = 16,
}
Name: CompareAttribute
Description: Provides an attribute that compares two properties.
Usage: [Compare(OtherProperty)]
Example:
public class Visitor
{
public string EmailAddress { get; set; }
[Compare("EmailAddress", ErrorMessage="Email Addresses Do Not Match." )]
public string ConfirmEmailAddress { get; set; }
}
Name: ConcurrencyCheckAttribute
Description: Specifies that a property participates in optimistic concurrency checks. ConcurrencyCheckAttribute is used to specify that a property/column has a concurrency mode of “fixed” in the EDM model. A fixed concurrency mode means that this property is part of the concurrency check of the entity during save operations and applies to scalar properties only.
Usage: [ConcurrencyCheckAttribute]
Example:
public class Book
{
public long BookId { get; set; }
public virtual string Title { get; set; }
public Author Author { get; set; }
[ConcurrencyCheckAttribute]
[TimestampAttribute]
public byte[] TimeStamp { get; set; }
}
Name: CreditCardAttribute
Description: Specifies that a data field value is a credit card number.
Usage: [CreditCardAttribute]
Example:
public class Buyer
{
public string Nombre { get; set; }
[CreditCardAttribute]
public string CardNumber { get; set; }
}
Name: CustomValidationAttribute
Description: Specifies a custom validation method that is used to validate a property or class instance.
Usage: [CustomValidation(typeof(Field), "Eval_function")]
Example:
public class CategoryMetadata
{
[CustomValidation(typeof(Category), "TestCategoryName")]
public object CategoryName { get; set; }
}
public static ValidationResult TestCategoryName(string pNewName, ValidationContext pValidationContext)
{
if (Regex.IsMatch(pNewName, @"^\d")) // cannot start with a digit
return new ValidationResult("Cannot start with a digit", new List<string> { "CategoryName" });
return ValidationResult.Success;
}
Name: DataTypeAttribute
Description: Specifies the name of an additional type to associate with a data field.
Usage: [DataType(DataType.*)]
Example:
public class DataTypeEntity
{
[DataType(DataType.Date, ErrorMessage = "Please enter a valid date (ex: 2/14/2011)")]
public DateTime SaleDate { get; set; }
[DataType(DataType.EmailAddress)]
public string EmailAddress { get; set; }
}
Name: DisplayAttribute
Description: Provides a general-purpose attribute that lets you specify localizable strings for types and members of entity partial classes.
Usage: [Display(Name = "*")]
Example:
public class SalesMan
{
[Required]
[DisplayName("Full Name :")]
public string Name { get; set; }
[Display(Name = "Email address")]
public string EmailAddress { get; set; }
}
Name: DisplayColumnAttribute
Description: Specifies the column that is displayed in the referred table as a foreign-key column.
Usage: [DisplayColumn("field to use as Foreign Key, Field to use for Sorting, ascending/descending)]
Example:
[DisplayColumn("City", "PostalCode", false)]
public partial class Address
{
}
Name: DisplayFormatAttribute
Description: Specifies how data fields are displayed and formatted by ASP.NET Dynamic Data.
Usage: [DisplayFormat(DataFormatString="*")]
Example:
public class Sale
{
// Display currency data field in the format $1,345.50.
[DisplayFormat(DataFormatString="{0:C}")]
public object StandardCost;
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy hh:mm}")]
public DateTime MyDate { get; set; }
}
Name: EditableAttribute
Description: Indicates whether a data field is editable.
Usage: [Editable(AllowEdit=bool,AllowInitialValue=bool)]
Example:
public class Person
{
[Editable(AllowEdit=false)]
public object Name { get; set; }
}
Name: EmailAddressAttribute
Description: Validates an email address.
Usage: [EmailAddress]
Example:
public class employee
{
public string Name{get; set;}
[EmailAddress]
public string Notification {get; set;}
}
Name: EnumDataTypeAttribute
Description: Enables a .NET Framework enumeration to be mapped to a data column.
Usage: [EnumDataType(typeof(Enum Type))]
Example:
public enum eReorderLvl {
zero = 0,
five = 5,
ten=10,
fifteen=15,
twenty=20,
twenty_five=25,
thirty=30
}
public class Product_MD {
[EnumDataType(typeof(eReorderLvl))]
public object ReorderLevel { get; set; }
}
Name: FileExtensionsAttribute
Description: Validates file name extensions.
Usage: [FileExtensions(Extensions="*")]
Example:
public class Cliente{
[FileExtensions(Extensions = "csv,txt",ErrorMessage = "Must choose .csv file.")]
public string ImportFile{ get; set; }
}
Name: FilterUIHintAttribute
Description: Represents an attribute that is used to specify the filtering behavior for a column.
Usage: [FilterUIHint("The name of the control to use for filtering.")]
Example:
MetadataType(typeof(Product_MD))]
public partial class Product {
private class Product_MD {
[FilterUIHint("MultiForeignKey")]
public object Category { get; set; }
[FilterUIHint("BooleanRadio")]
public object Discontinued { get; set; }
}
}
Name: KeyAttribute
Description: Denotes one or more properties that uniquely identify an entity.
Usage: [Key]
Example:
public class Cliente{
[Key]
public int Id { get; set; }
public string name { get; set; }
}
Name: MaxLengthAttribute
Description: Specifies the maximum length of array or string data allowed in a property.
Usage: [MaxLength(Length)]
Example:
public class Customer
{
public virtual string CustomerID { get; set; }
[MaxLength(50, ErrorMessage="Name can not be longer than 50 characters." )]
public virtual string CompanyName { get; set; }
}
Name: MetadataTypeAttribute
Description: Specifies the metadata class to associate with a data model class.It indicates that a data model class has an associated
metadata
class. The MetadataType
attribute gets a type parameter to specify which type is holding the metadata
for the classUsage: [MetadataType(typeof(MetaData))]
Example:
public class CRMTypeMetadata
{
[ScaffoldColumn(false)]
public int TypeID { get; set; }
[StringLength(100)]
public string Url { get; set; }
}
[MetadataType(typeof(CRMTypeMetadata))]
public partial class CRMType
{
}
Name: MinLengthAttribute
Description: Specifies the minimum length of array or string data allowed in a property.
Usage: [MinLength(Length)]
Example:
public class Customer
{
public virtual string CustomerID { get; set; }
[MinLength(3, ErrorMessage="Name can not be shorter than 3 characters." )]
public virtual string CompanyName { get; set; }
}
Name: PhoneAttribute
Description: Specifies that a data field value is a well-formed phone number using a regular expression for phone numbers.
Usage: [Phone]
Example:
public class Customer
{
public virtual string CustomerID { get; set; }
[Phone]
public virtual string Phone_Number { get; set; }
}
Name: RangeAttribute
Description: Specifies the numeric range constraints for the value of a data field.
Usage: [Range(Double,Double)], [Range(Int32,Int32)], [Range(Type,String,String)]
Example:
public class Item
{
public int Id { get; set; }
[Range(10, 1000, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
public Double Weight { get; set; };
}
Name: RegularExpressionAttribute
Description: Specifies that a data field value in ASP.NET Dynamic Data must match the specified regular expression.
Usage: [RegularExpression(@"Regular_Expresion")]
Example:
public class Customer
{
[RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter correct email")]
public string Email { get; set; }
}
Name: RequiredAttribute
Description: Specifies that a data field value is required.
Usage: [Required()]
Example:
public class Customer
{
[Required]
public virtual string CustomerID { get; set; }
public virtual string CompanyName { get; set; }
}
Name: ScaffoldColumnAttribute
Description: Specifies whether a class or data column uses scaffolding.
Usage: [ScaffoldColumn(true)]
Example:
public class ProductMetadata
{
[ScaffoldColumn(true)]
public object ProductID;
[ScaffoldColumn(false)]
public object ThumbnailPhotoFileName;
}
Name: ScaffoldTableAttribute
Description: Specifies whether a class or data table uses scaffolding.
Usage: [ScaffoldTable(bool)]
Example:
[MetadataType (typeof(ErrorLogMetada))]
[ScaffoldTable(false)]
public partial class ErrorLog
{
}
public class ErrorLogMetada
{
}
Name: StringLengthAttribute
Description: Specifies the minimum and maximum length of characters that are allowed in a data field.
Usage: [StringLength(int maximumLength)]
Example:
public class ProductMetadata
{
[StringLength(4, ErrorMessage = "The ThumbnailPhotoFileName value cannot exceed 4 characters. ")]
public object ThumbnailPhotoFileName;
}
Name: TimestampAttribute
Description: Specifies the data type of the column as a row version.Also specifies that this column will be included in the Where clause of Update and Delete commands sent to the database, For concurrency cheking.
Usage: [Timestamp]
Example:
public class Person
{
public Int64 Id { get; set; }
public string Name { get; set; }
[Timestamp]
public Byte[] Timestamp { get; set; }
}
Name: UIHintAttribute
Description: Specifies the template or user control that Dynamic Data uses to display a data field.
Usage: [UIHintAttribute(string uiHint)]
Example:
public partial class ProductMetadata
{
[UIHint("UnitsInStock")]
[Range(100, 10000,
ErrorMessage = "Units in stock should be between {1} and {2}.")]
public object UnitsInStock;
}
Name: UrlAttribute
Description: Provides URL validation.
Usage: [Url]
Example:
public class MyModel
{
[Url]
public string ServerAddress {get; set;}
}
And that, my Friend, It's all!
A pesar de los años que han pasado, esto me resultó sumamente útil Mario, te agradezco mucho. Un abrazo desde Monterrey!
ReplyDelete