In this article, we’ll explore configuring entities in Entity Framework Core (EF Core). We’ll walk through two popular methods: Attributes (Data Annotations) and Fluent API. Along the way, we’ll mix both methods—using attributes for the Product
entity and Fluent API for configuring the Category
entity.
We’ll cover:
- Configuring entities using attributes (data annotations)
- Configuring entities using Fluent API
- Applying a migration and updating the database
- Comparing both approaches
1. Configuring Entities Using Attributes
Attributes (Data Annotations) allow you to configure entity properties directly in the class definition. This method is simple and convenient for basic configurations.
Example:
We’ll add attributes to the Product
entity.
In the ProductDomain project, open the Product.cs
class and modify it as follows:
namespace ProductDomain
{
public class Product
{
public int Id { get; set; }
[Required] // Ensures the Name is required
[MaxLength(100)] // Limits the Name length to 100 characters
public string Name { get; set; }
[Range(0, 10000)] // Limits the price to a range
public decimal Price { get; set; }
public int CategoryId { get; set; }
[ForeignKey("CategoryId")] // Defines a foreign key relationship to the Category
public Category Category { get; set; }
}
}
2. Configuring Entities Using Fluent API
Fluent API gives you more flexibility and power to configure entities beyond what attributes can offer. In this example, we’ll use Fluent API to configure the Category
entity.
In the ProductData project, modify the AppDbContext
class:
using Microsoft.EntityFrameworkCore;
using ProductDomain;
namespace ProductData
{
public class AppDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Inventory> Inventories { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"your-connection-string");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Fluent API configuration for Category entity
modelBuilder.Entity<Category>(entity =>
{
entity.HasKey(c => c.Id); // Set primary key
entity.Property(c => c.Name)
.IsRequired()
.HasMaxLength(50); // Limit the Name length to 50 characters
// Configure relationship with Products
entity.HasMany(c => c.Products)
.WithOne(p => p.Category)
.HasForeignKey(p => p.CategoryId);
});
}
}
}
3. Updating the Database
After configuring your entities, you need to apply the changes to the database. In the ProductData project, follow these steps:
- Open the Package Manager Console from Tools > NuGet Package Manager > Package Manager Console.
- Set the Default Project to ProductData.
- Run the following commands to create a migration and update the database:
Add-Migration ConfigEntities
Update-Database
This will create the necessary database tables based on the updated configuration.
4. Comparison: Attributes vs. Fluent API
Feature | Attributes | Fluent API |
---|---|---|
Simplicity | Easy to implement directly in the entity class | Requires additional setup in DbContext |
Location | Defined in the entity class | Defined in the DbContext |
Complex Configurations | Limited to basic validation and relationships | Supports advanced configurations like composite keys and detailed relationships |
Use Case | Best for simple scenarios | Ideal for more complex scenarios requiring greater flexibility |
Conclusion
In this article, we’ve explored two common methods of configuring entities in EF Core: Attributes and Fluent API. We used attributes to configure the Product
entity and Fluent API for the Category
entity, demonstrating how you can mix both methods depending on your needs.
We also walked through applying these configurations to a database using migrations. In the next article, we’ll explore configuring more advanced relationships and handling different entity mapping scenarios.
Source Code EFCoreDemo
Top comments (0)