Tutorials Entity Framework Core Tutorial
Data Annotations in EF Core
Data Annotations in EF Core: free step-by-step lesson with examples, common mistakes, and interview tips — part of Entity Framework Core Tutorial on Toolliyo Academy.
On this page
Entity Framework Core Tutorial · Lesson 13 of 100
Data Annotations in EF Core
Beginner → Intermediate → Advanced → Professional
Beginner · 1 — Foundations · ~6 min · Module 2: Code First Approach
What is this?
Data annotations are attributes like [Required], [MaxLength], and [Column] on entity properties. EF Core reads them when building the model for schema and optional validation.
Why should you care?
ShopNest product names must be required and capped at 200 characters — annotations express that at the property without Fluent API boilerplate.
See it live — copy this example
Paste into a .NET project with EF Core packages, then run with LocalDB/SQL Server (dotnet ef / dotnet run).
public class Product
{
public int Id { get; set; }
[Required, MaxLength(200)]
public string Name { get; set; } = "";
[Range(0.01, 9999999)]
public decimal Price { get; set; }
[MaxLength(50)]
public string Sku { get; set; } = "";
}
What happened?
- Required maps to NOT NULL.
- MaxLength sets nvarchar length.
- Range can participate in validation before SaveChanges if you enable it.
Practice next
- Annotate Product and Customer.Email with Required and MaxLength.
- Run dotnet ef migrations add AnnotateProducts and read Up() for column changes.
- Attempt save with empty Name and observe validation behavior.
- Add [Column(TypeName = "decimal(18,2)")] on Price and regenerate migration.
- Apply [EmailAddress] on Customer.Email for API-level validation synergy.
Remember
Annotations configure columns and simple validation. Good for straightforward rules on properties. Complex relationships still prefer Fluent API.
ShopNest catalog constraints
Product.Name annotations enforce NOT NULL and length before bad rows reach SQL Server.
Outcome: Migration creates nvarchar(200) matching Flipkart-style title limits.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!