What is Entity Framework?
Entity Framework (EF) is Microsoft’s modern Object-Relational Mapper (ORM) for .NET applications. It allows developers to interact with a database using strongly typed C# classes instead of manual SQL queries. Improving productivity, maintainability, and reducing risk of human error.
Why We Use It
At Pfann.Tech, we use EF as a bridge between our ASP.NET applications and SQL Server databases. It enables us to write clean, reusable, and secure data access logic while maintaining complete control over relationships, migrations, and performance optimization.
Example: Defining a Model
In EF, each table is represented as a model class. Attributes and conventions define how it maps to the database:
public class Client
{
[Key]
public int ClientId { get; set; }
[Required, MaxLength(100)]
public string ClientName { get; set; } = string.Empty;
[MaxLength(255)]
public string? Email { get; set; }
public bool IsActive { get; set; } = true;
public DateTime CreatedDate { get; set; } = DateTime.UtcNow;
}
Example: Defining a DbContext
The DbContext class acts as a session for interacting with the database, tracking changes, handling queries, and managing transactions.
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions options)
: base(options) { }
public DbSet<Client> Clients { get; set; } = default!;
}
Example: Querying Data
EF allows expressive LINQ queries that automatically translate to SQL:
// Fetch all active clients ordered alphabetically
var clients = await _context.Clients
.Where(c => c.IsActive)
.OrderBy(c => c.ClientName)
.ToListAsync();
Example: Adding and Saving Records
Adding data is simple and automatically generates the proper SQL under the hood:
var newClient = new Client
{
ClientName = "Example Co.",
Email = "contact@example.com"
};
_context.Clients.Add(newClient);
await _context.SaveChangesAsync();
Example: Using Relationships
EF supports one-to-many, many-to-many, and one-to-one relationships using navigation properties and foreign keys:
public class EngagementLetter
{
public int EngagementLetterId { get; set; }
public int ClientId { get; set; }
[ForeignKey(nameof(ClientId))]
public Client Client { get; set; } = default!;
}
How It Works for You
Entity Framework allows Pfann.Tech to develop faster, deploy cleaner code, and reduce long-term maintenance costs. By combining EF with SQL Server, we deliver secure, high-performance applications that scale alongside your business.