Entity Framework Core Interview Question #10
What are data annotations in EF Core?
EF Core Fundamentals & DbContext Junior Beginner
Quick Interview Answer
Data annotations are attributes placed on entity classes or properties to configure validation or aspects of EF Core mapping. Common examples include Key, Required, MaxLength, Column, Table, and NotMapped.
Detailed Explanation
Data annotations are attributes placed on entity classes or properties to configure validation or aspects of EF Core mapping. Common examples include Key, Required, MaxLength, Column, Table, and NotMapped.
They are convenient for simple configuration because the rules are close to the model. However, they add persistence-related metadata to entity classes and cannot express every EF Core mapping.
For complex mapping, Fluent API configuration is generally more powerful.
Code Example
public class Product
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(200)]
public string Name { get; set; } = string.Empty;
}