What are Data Annotations and how are they used in Entity Framework Core?

Beginner

Answer

Data Annotations are attributes applied to entity classes and properties to configure the model and validation rules.
Common annotations:

public class Product
{
    [Key]
    public int ProductId { get; set; }
    [Required]
    [MaxLength(100)]
    public string Name { get; set; }
    [Column(TypeName = "decimal(18,2)")]
    public decimal Price { get; set; }
    [ForeignKey("CategoryId")]
    public Category Category { get; set; }
    [NotMapped]
    public string DisplayName { get; set; }
}

Categories:

  • Key attributes: [Key], [DatabaseGenerated]
  • Validation: [Required], [MaxLength], [Range]
  • Schema: [Table], [Column], [NotMapped]
  • Relationships: [ForeignKey], [InverseProperty]