Data Annotations in Entity Framework are used to define constraints, validations, and other data-related attributes directly in your C# code. They are used to configure the database schema, data types, and validation rules for your entities. Here’s a list of common Data Annotations in Entity Framework along with an example code:
In Data Annotations, we have two types of namespaces that have their specific in-build types.
1. System.ComponentModel.DataAnnotations
incorporate the subsequent attributes that affect and check the size or nullability of the column.
2. System.ComponentModel.DataAnnotations.Schema
namespace comprises the subsequent attributes that reshape the schema of the database.
Why and When to Use Data Annotations
Data annotations (DAs) are used to provide metadata to your code, which can help to control the behavior of your code. By using DAs in your code, you can ensure that your application is more robust, reliable, and maintainable. Here are some reasons why and when you might use data annotations:
- Data Validation — DAs can be used to enforce data validation rules, ensuring that data entered into your application meets certain requirements. For example, the [Required] annotation can be used to ensure that a property is not null or empty, and the [Range] annotation can be used to ensure that a numeric property falls within a specific range.
- Display Formatting — DAs can be used to control how data is displayed in your application’s user interface. For example, the [DisplayFormat] annotation can be used to control the formatting of a date or time property.
- Data Mapping — DAs can be used to specify how your entity is mapped to the database. For example, the [Key] annotation can be used to specify the primary key for your entity, and the [ForeignKey] annotation can be used to specify the foreign key for a navigation property.
- Model Binding — DAs can be used to control how data is bound to your application’s model. For example, the [Bind] annotation can be used to specify which properties should be included or excluded when binding to a model.
- Concurrency Control — DAs can be used to handle concurrency issues when updating data. For example, the [Timestamp] annotation can be used to include a timestamp property in your entity, which can be used to detect when data has been modified by another user.
Here, is a list of some important Data Annotation Attributes.
1 2 3 4 | [Required(ErrorMessage = "Name is Required")] public string Name { get; set; } |
1 2 3 4 | [DisplayName("Enter Your Name: ")] public string Name { get; set; } |
1 2 3 4 | [StringLength(50, MinimumLength = 3)] public string Name { get; set; } |
1 2 3 4 | [Range(1,120, ErrorMessage ="Age must be between 1-120 in years.")] public int Age { get; set; } |
1 2 3 | [Bind(Exclude = "Id")] |
1 2 3 4 | [ScaffoldColumn(false)] public int Id { get; set; } |
1 2 3 4 | [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy hh:mm:ss tt}")] public System.DateTime? HireDate { get; set; } |
1 2 3 4 | [ReadOnly(true)] public string Name { get; private set; } |
1 2 3 4 | [MaxLength(50)] public string Name { get; set; } |
1 2 3 4 | [DataType(DataType.CreditCard)] public string Name { get; set; } |
1 2 3 4 | [System.ComponentModel.DataAnnotations.Compare("Email", ErrorMessage = "Email Not Matched")] public string ConfirmEmail { get; set; } |
1 2 3 4 5 6 7 | [Required(ErrorMessage = "Email ID is Required")] [DataType(DataType.EmailAddress)] [MaxLength(50)] [RegularExpression(@ "[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Incorrect Email Format")] public string Email { get; set;} |
1 2 3 4 5 | [DataType(DataType.PhoneNumber)] [RegularExpression(@"^\(?([0-9]{2})[-. ]?([0-9]{4})[-. ]?([0-9]{3})[-. ]?([0-9]{3})$", ErrorMessage = "Not a valid Phone number")] public string Name { get; set; } |
Output format:Â 91-1234-567-890
1 2 3 4 | [Url][Required] public string URL { get; set; } |
1 2 3 4 | [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Incorrect Email Format")] public string Email { get; set; } |
1 2 3 4 | [DataType(DataType.EmailAddress)] public string Email { get; set; } |
1 2 3 4 | [System.Web.Mvc.HiddenInput(DisplayValue = false)] public string Name { get; set; } |
1. Table:Â Specifies the name of the database table associated with an entity class.
1 2 3 4 5 6 7 | [Table("Employees")] public class Employee { // Properties... } |
2. Column:Â Specifies the name and data type of a database column associated with a property.
1 2 3 4 | [Column("FullName", TypeName = "nvarchar(100)")] public string Name { get; set; } |
3. Index:Â Specifies an index on one or more columns of a table.
1 2 3 4 5 6 7 8 | [Index("IX_FirstNameLastName", 1, IsUnique = true)] [Index("IX_FirstNameLastName", 2, IsUnique = true)] public string FirstName { get; set; } [Index("IX_FirstNameLastName", 3, IsUnique = true)] public string LastName { get; set; } |
4. ForeignKey:Â Specifies a foreign key relationship between entities.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class Student { public int StudentID { get; set; } public string StudentName { get; set; } [ForeignKey("Standard")] public int StandardId { get; set; } public Standard Standard { get; set; } } public class Standard { public int StandardId { get; set; } public string StandardName { get; set; } public ICollection<Student> Students { get; set; } } |
5. NotMapped:Â Excludes a property or class from being mapped to the database.
1 2 3 4 | [NotMapped] public int CalculatedValue { get; set; } |
6. DatabaseGenerated: Defines how a value for a database column is generated, such as identity, computed, or none.
1 2 3 4 | [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int EmployeeId { get; set; } |
7. InverseProperty:Â Specifies the inverse navigation property in a many-to-many relationship.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class Student { public int StudentId { get; set; } public string Name { get; set; } [InverseProperty("Students")] public ICollection<Course> Courses { get; set; } } public class Course { public int CourseId { get; set; } public string Title { get; set; } [InverseProperty("Courses")] public ICollection<Student> Students { get; set; } } |
8. ComplexType: Marks a class as a complex type, which is a class that doesn’t have a primary key and is used as part of another entity.
1 2 3 4 5 6 7 8 9 | [ComplexType] public class Address { public string Street { get; set; } public string City { get; set; } public string State { get; set; } } |
9. DefaultValue: DefaultValue data annotation is used to specify a default value for a property.
1 2 3 4 | [DefaultValue(0)] public int Quantity { get; set; } |
These are some of the commonly used Data Annotations in Entity Framework. You can use these attributes to define the structure, constraints, and relationships of your data model when working with Entity Framework.
Leave a Comment