In this lesson, you will learn how to use attribute-based metadata to enforce database schema constraints directly within your C# domain entities.
Declarative Schema Constraints
While Entity Framework Core can infer a lot about your database from your class structures, sometimes you need to be explicit about column requirements like length, nullability, or uniqueness. Data Annotations allow you to decorate your entity properties with attributes that EF Core translates into schema-level constraints when it migrates your model to the database.
By keeping these rules in your C# code, you maintain a "single source of truth" for both your application logic and your database design.
Applying Metadata Attributes
Consider a User entity where we want to ensure the Username is required and the Email doesn't exceed a specific length. Instead of writing separate configuration code, we apply attributes directly to the properties:
using System.ComponentModel.DataAnnotations;
public class User
{
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Username { get; set; }
[EmailAddress]
[MaxLength(256)]
public string Email { get; set; }
}
When EF Core scans your model, it inspects these attributes to build the schema. For example, [Required] tells the provider to generate a NOT NULL constraint in SQL, while [StringLength(50)] explicitly sets the column type to NVARCHAR(50).
Why Use Annotations?
Beyond schema generation, these annotations provide a dual benefit. They are used by the underlying System.ComponentModel.DataAnnotations validation engine. This means that if you are using these entities in a web application, ASP.NET Core can automatically validate the object state before it even touches the database, providing a seamless bridge between your API surface and your storage layer.
It keeps your entity definitions clean and expressive, ensuring that your intent is clear to any developer reading the code—and to the database engine creating the tables.
Key Takeaway: Data Annotations allow you to enforce database-level schema constraints declaratively using C# attributes, keeping your domain entities self-documenting and integrated with both EF Core migrations and model validation.