Entity Framework
Data Insertion
EF Model
ORM
.NET Development

Insert data using Entity Framework model

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

In Entity Framework, inserting data means creating an entity object, adding it to the relevant DbSet, and calling SaveChanges or SaveChangesAsync. The framework tracks the new entity, generates the required SQL INSERT, and updates generated keys back onto the object after the database commit.

Basic Insert Flow

A minimal EF Core model looks like this:

csharp
1using Microsoft.EntityFrameworkCore;
2
3public class AppDbContext : DbContext
4{
5    public DbSet<Customer> Customers => Set<Customer>();
6
7    protected override void OnConfiguring(DbContextOptionsBuilder options)
8        => options.UseSqlServer("Server=.;Database=DemoDb;Trusted_Connection=True;TrustServerCertificate=True");
9}
10
11public class Customer
12{
13    public int Id { get; set; }
14    public string Name { get; set; } = "";
15    public string Email { get; set; } = "";
16}

To insert a row:

csharp
1using var db = new AppDbContext();
2
3var customer = new Customer
4{
5    Name = "Ada Lovelace",
6    Email = "[email protected]"
7};
8
9db.Customers.Add(customer);
10db.SaveChanges();
11
12Console.WriteLine(customer.Id);

After SaveChanges, EF sends the insert to the database and populates customer.Id if the key is database-generated.

What Add Actually Does

Add does not immediately talk to the database. It marks the entity state as Added inside the change tracker. The actual SQL is generated later when you call SaveChanges.

That distinction matters because you can stage several inserts first:

csharp
db.Customers.Add(new Customer { Name = "Grace", Email = "[email protected]" });
db.Customers.Add(new Customer { Name = "Linus", Email = "[email protected]" });
db.SaveChanges();

EF then writes both changes in one save operation.

Async Insert

In web applications and other scalable server code, use the async path:

csharp
1using var db = new AppDbContext();
2
3var customer = new Customer
4{
5    Name = "Margaret Hamilton",
6    Email = "[email protected]"
7};
8
9await db.Customers.AddAsync(customer);
10await db.SaveChangesAsync();

Async does not change the data model. It only changes how the database work is awaited.

EF also handles relationships. If an order belongs to a customer, you can insert both through navigation properties:

csharp
1public class Order
2{
3    public int Id { get; set; }
4    public string Number { get; set; } = "";
5    public int CustomerId { get; set; }
6    public Customer Customer { get; set; } = null!;
7}
8
9var customer = new Customer
10{
11    Name = "Nora",
12    Email = "[email protected]"
13};
14
15var order = new Order
16{
17    Number = "ORD-1001",
18    Customer = customer
19};
20
21db.Add(order);
22db.SaveChanges();

EF tracks both entities and inserts them in the required order.

Validate Before Saving

Entity Framework is not a substitute for input validation. Check required fields, uniqueness rules, and domain constraints before calling SaveChanges. Database exceptions are still possible, but good validation keeps them from becoming your normal control flow.

Keep DbContext Lifetime Short

A DbContext is designed for a unit of work, not for the lifetime of the whole application process. Use one context for one operation, request, or transaction scope, then dispose it.

That keeps tracking state small and prevents stale entities from accumulating.

Common Pitfalls

The most common mistake is creating an entity object and forgetting to call SaveChanges, which means nothing is written to the database. Another is keeping one DbContext alive too long and then wondering why stale tracked entities or unexpected updates appear.

Developers also sometimes expect Add itself to execute SQL immediately. It does not. Finally, if the database generates keys, do not assume the entity has its final key value until the save operation completes.

Summary

  • Create the entity, add it to the DbSet, then call SaveChanges or SaveChangesAsync.
  • 'Add only marks the entity as new; the database write happens during save.'
  • EF can insert multiple related entities in one tracked unit of work.
  • Keep DbContext lifetimes short and validate data before saving.
  • Database-generated keys are usually available on the entity after the save succeeds.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.