EF Code first provides set of DataAnnotation attributes which you can apply on your domain classes and properties. You have to include System.ComponentModel.DataAnnotations namespace to use DataAnnotation attributes. DataAnnotation basically includes attributes for server side validations and database related attributes.
Annotation Attribute | Description |
---|---|
Required | The Required annotation will force EF (and MVC) to ensure that property has data in it. |
MinLength | MinLength annotation validates property whether it has minimum length of array or string. |
MaxLength | MaxLength annotation maximum length of property which in-tern set maximum length of column in the database |
StringLength | Specifies the minimum and maximum length of characters that are allowed in a data field. |
Database Schema related Attributes:
Annotation Attribute | Description |
---|---|
Table | Specify name of the DB table which will be mapped with the class |
Column | Specify column name and datatype which will be mapped with the property |
Key | Mark property as EntityKey which will be mapped to PK of related table. |
ComplexType | Mark the class as complex type in EF. |
Timestamp | Mark the property as a non-nullable timestamp column in the database. |
ForeignKey | Specify Foreign key property for Navigation property |
NotMapped | Specify that property will not be mapped with database |
ConcurrencyCheck | ConcurrencyCheck annotation allows you to flag one or more properties to be used for concurrency checking in the database when a user edits or deletes an entity. |
DatabaseGenerated | DatabaseGenerated attribute specifies that property will be mapped to Computed column of the database table. So the property will be read-only property. It can also be used to map the property to identity column (auto incremental column). |
InverseProperty | InverseProperty is useful when you have multiple relationship between two classes. |
DataAnnotation example:
[Table("StudentInfo")] public class Student { public Student(){ } [Key] public int SID { get; set; } [Required(ErrorMessage="Student Name is Required" )] [Column("Name", TypeName="ntext")] [MaxLength(20), MinLength(2, ErrorMessage="Student name can not be 2 character or less")] public string StudentName { get; set; } [NotMapped] public int? Age { get; set; } [ConcurrencyCheck()] [Timestamp] public Byte[] LastModifiedTimestamp { get; set; } public int? MathScore { get; set; } public int? ScienceScore { get; set; } [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public int? TotalScore { get; set; } public int StdId { get; set; } [ForeignKey("StdId")] public virtual Standard Standard { get; set; } }
Download DataAnnotation Sample project:
No comments:
Post a Comment