In a previous post, we saw how to manage a PostgreSQL database using C# and Dapper, writing the SQL statements by hand.
In this post, we will build the same application using Entity Framework Core with a Code First approach and then, we will add a new feature: the use of Stored Procedures (and Functions) defined in PostgreSQL.
Finally, instead of Swagger, we will use Scalar to test our Minimal API.
We will keep the same domain of the previous post: a table called User, so defined:
CREATE TABLE public."User" (
"Id" SERIAL PRIMARY KEY,
"Username" VARCHAR(100),
"Password" VARCHAR(100),
"Email" VARCHAR(250)
);
The difference is that this time we will not write this SQL but, we will describe the table in C# and EF Core will create it for us.
First of all, we run a Docker container for PostgreSQL (if we still have the container of the previous post, we can reuse it):
docker run --name db_postgres -e POSTGRES_USER=Admin -e POSTGRES_PASSWORD=Pass123 -p 5432:5432 -d postgres


This time we don’t create the database manually: we will call it TestDBEF and EF Core will create it for us, together with the table.
Now, we create an ASP.NET Core Web API project called TestPostgreSQL (with Minimal API) and we install the packages via NuGet that we will use in the project:
- Npgsql.EntityFrameworkCore.PostgreSQL: the EF Core provider for PostgreSQL
- Microsoft.EntityFrameworkCore.Design: design time tools required to create the migrations
- Scalar.AspNetCore: to test the API (it replaces Swagger UI)
- Microsoft.AspNetCore.OpenApi: to generate the OpenAPI document used by Scalar
- xUnit: for unit testing
- Moq: for mocking dependencies during testing
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Scalar.AspNetCore
dotnet add package Microsoft.AspNetCore.OpenApi
dotnet add package xunit
dotnet add package Moq
Then, we add the connection string in the configuration file:
[APPSETTINGS.JSON]
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Username=Admin;Password=Pass123;Database=TestDBEF"
},
"AllowedHosts": "*"
}
Now, we define the User entity using a plain C# class (a POCO): no SQL, no attributes.
EF Core will map it to the User table:
[USER.CS]
namespace TestPostgreSQL;
public class User
{
public int Id { get; set; }
public string Username { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
}
To describe how the entity maps to the database, we use a configuration class that implements IEntityTypeConfiguration<User>:
[USERCONFIGURATION.CS]
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace TestPostgreSQL;
public class UserConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
// Map the entity to the table public."User"
builder.ToTable("User", "public");
// Primary key with auto increment
builder.HasKey(u => u.Id);
builder.Property(u => u.Id).ValueGeneratedOnAdd();
builder.Property(u => u.Username).IsRequired().HasMaxLength(100);
builder.Property(u => u.Password).IsRequired().HasMaxLength(100);
builder.Property(u => u.Email).IsRequired().HasMaxLength(250);
}
}
Next, we define the DbContext, the heart of EF Core: it exposes the tables as DbSet properties and applies the configuration we just created:
[APPDBCONTEXT.CS]
using Microsoft.EntityFrameworkCore;
namespace TestPostgreSQL;
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
// The DbSet represents the User table
public DbSet<User> Users => Set<User>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Apply every IEntityTypeConfiguration found in the assembly
modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
}
}
As we saw in the post C# – Management of a SQLite database with EF, the dotnet-ef tools sometimes are not able to create the DbContext at design time, so we add a design-time factory (it is used only by the command line tools):
[APPDBCONTEXTFACTORY.CS]
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
namespace TestPostgreSQL;
public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
public AppDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
optionsBuilder.UseNpgsql("Host=localhost;Username=Admin;Password=Pass123;Database=TestDBEF");
return new AppDbContext(optionsBuilder.Options);
}
}
Now we can create the first migration. This is what “Code First” is really about: from our C# model, EF Core generates the SQL schema for us:
dotnet tool install --global dotnet-ef
dotnet ef migrations add InitialCreate
dotnet ef database update
If we open the database, we can see that EF Core created the database TestDBEF, the table User and the table __EFMigrationsHistory, used to keep track of the migrations already applied:

STORED PROCEDURES
Before writing the code, we have to say something about Stored Procedures in PostgreSQL.
In SQL Server, a Stored Procedure can do everything: change data, return a result set, return output parameters. In PostgreSQL, instead, we have two different objects:
- PROCEDURE: (available from PostgreSQL 11) it doesn’t return a result set and we call it with CALL. It is the right tool when we want to execute an operation, for example a DELETE.
- FUNCTION: it can return a value or a set of rows and we call it with a SELECT. It is the right tool when we want to read data.
So, we will define one object for each type:
- a function called fn_get_users_by_domain, that returns all the users with an email of a specific domain
- a procedure called sp_delete_users_by_domain, that deletes all the users with an email of a specific domain
Since we are using Code First, we don’t want to create them manually in the database, otherwise our database would not be reproducible. For this reason, we will create them inside a migration.
First of all, we create an empty migration:
dotnet ef migrations add AddStoredProcedures
EF Core generates a migration with the Up and Down methods empty, and we fill them using the method Sql:
[ADDSTOREDPROCEDURES.CS]
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace TestPostgreSQL.Migrations;
public partial class AddStoredProcedures : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
// Function: returns the users with an email of a specific domain
migrationBuilder.Sql("""
CREATE OR REPLACE FUNCTION public.fn_get_users_by_domain(p_domain text)
RETURNS TABLE ("Id" integer, "Username" varchar, "Password" varchar, "Email" varchar)
LANGUAGE sql
AS $$
SELECT u."Id", u."Username", u."Password", u."Email"
FROM public."User" u
WHERE u."Email" ILIKE '%@' || p_domain
ORDER BY u."Username";
$$;
""");
// Procedure: deletes the users with an email of a specific domain
migrationBuilder.Sql("""
CREATE OR REPLACE PROCEDURE public.sp_delete_users_by_domain(p_domain text)
LANGUAGE plpgsql
AS $$
BEGIN
DELETE FROM public."User"
WHERE "Email" ILIKE '%@' || p_domain;
END;
$$;
""");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("DROP PROCEDURE IF EXISTS public.sp_delete_users_by_domain(text);");
migrationBuilder.Sql("DROP FUNCTION IF EXISTS public.fn_get_users_by_domain(text);");
}
}
Two important things:
- the columns returned by the function have the same names (and the same case, thanks to the double quotes) of the columns of the User table. We need this because, when we call the function from EF Core, it will map the result to the User entity using the column names
- thanks to the Down method, if we revert the migration, the function and the procedure will be removed
Now, we apply the migration:
dotnet ef database update
and we can check that the function and the procedure have been created, running this query in the database (prokind “f” means function and “p” means procedure):
SELECT proname, prokind FROM pg_proc WHERE proname LIKE 'fn_%' OR proname LIKE 'sp_%';

Now, we define the repository. We keep the same methods of the previous post and we add two new methods, one for the function and one for the procedure.
To keep the post simple, we remove the Service layer and we will use the repository directly in the Minimal API:
[IUSERREPOSITORY.CS]
namespace TestPostgreSQL;
public interface IUserRepository
{
Task<IEnumerable<User>> GetAllAsync();
Task<User?> GetByIdAsync(int id);
Task AddAsync(User user);
Task UpdateAsync(User user);
Task DeleteAsync(int id);
// Methods that use the Function and the Stored Procedure
Task<IEnumerable<User>> GetByDomainAsync(string domain);
Task DeleteByDomainAsync(string domain);
}
In the previous post, the UserRepository opened a connection, wrote a SQL string, added the parameters and mapped the results. Now, the repository receives the AppDbContext and works with LINQ.
For the function, we use the method FromSqlInterpolated and for the procedure the method ExecuteSqlInterpolatedAsync: in both cases, the values that we insert in the string are not concatenated but they are converted to SQL parameters, so we are safe from SQL injection:
[USERREPOSITORY.CS]
using Microsoft.EntityFrameworkCore;
namespace TestPostgreSQL;
public class UserRepository(AppDbContext context) : IUserRepository
{
// LINQ query to read all users
// AsNoTracking: read-only scenario, we do not need change tracking
public async Task<IEnumerable<User>> GetAllAsync()
{
return await context.Users
.AsNoTracking()
.ToListAsync();
}
// LINQ query to get a single user by id
public async Task<User?> GetByIdAsync(int id)
{
return await context.Users
.AsNoTracking()
.FirstOrDefaultAsync(u => u.Id == id);
}
// Add a new user: EF Core generates the INSERT and sets the generated Id
public async Task AddAsync(User user)
{
try
{
await context.Users.AddAsync(user);
await context.SaveChangesAsync();
}
catch (DbUpdateException ex)
{
Console.WriteLine($"Error: {ex.Message}");
throw new Exception("An error occurred while inserting the user into the database.", ex);
}
}
// Update an existing user: EF Core tracks the changes and generates the UPDATE
public async Task UpdateAsync(User user)
{
try
{
var existingUser = await context.Users.FindAsync(user.Id);
if (existingUser is null)
return;
existingUser.Username = user.Username;
existingUser.Password = user.Password;
existingUser.Email = user.Email;
await context.SaveChangesAsync();
}
catch (DbUpdateException ex)
{
Console.WriteLine($"Error: {ex.Message}");
throw new Exception("An error occurred while updating the user in the database.", ex);
}
}
// Delete a user by id: EF Core generates the DELETE
public async Task DeleteAsync(int id)
{
var user = await context.Users.FindAsync(id);
if (user is null)
return;
context.Users.Remove(user);
await context.SaveChangesAsync();
}
// Call the FUNCTION fn_get_users_by_domain
// The result is mapped to the User entity and we can still compose it with LINQ
public async Task<IEnumerable<User>> GetByDomainAsync(string domain)
{
return await context.Users
.FromSqlInterpolated($"SELECT * FROM public.fn_get_users_by_domain({domain})")
.AsNoTracking()
.ToListAsync();
}
// Call the PROCEDURE sp_delete_users_by_domain
// A procedure doesn't return rows so, we use ExecuteSqlInterpolatedAsync with CALL
public async Task DeleteByDomainAsync(string domain)
{
await context.Database
.ExecuteSqlInterpolatedAsync($"CALL public.sp_delete_users_by_domain({domain})");
}
}
Now, we modify the file Program.cs where, we register the DbContext, we configure Scalar and we define the Minimal API.
Starting from .NET 9, Swagger UI is not included anymore in the template: the framework generates the OpenAPI document (MapOpenApi) and Scalar uses it to show a UI where we can test all endpoints:
[PROGRAM.CS]
using Microsoft.EntityFrameworkCore;
using Scalar.AspNetCore;
using TestPostgreSQL;
var builder = WebApplication.CreateBuilder(args);
// OpenAPI document (used by Scalar)
builder.Services.AddOpenApi();
// Register the DbContext using the PostgreSQL provider and the connection string
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
// Register the repository (Scoped, like the DbContext)
builder.Services.AddScoped<IUserRepository, UserRepository>();
var app = builder.Build();
app.UseHttpsRedirection();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
// Scalar UI available at /scalar/v1
app.MapScalarApiReference();
}
app.MapGet("/users", async (IUserRepository userRepository) =>
await userRepository.GetAllAsync());
app.MapGet("/users/{id:int}", async (int id, IUserRepository userRepository) =>
{
var user = await userRepository.GetByIdAsync(id);
return user is not null ? Results.Ok(user) : Results.NotFound();
});
app.MapPost("/users", async (User user, IUserRepository userRepository) =>
{
await userRepository.AddAsync(user);
return Results.Created($"/users/{user.Id}", user);
});
app.MapPut("/users/{id:int}", async (int id, User user, IUserRepository userRepository) =>
{
var existingUser = await userRepository.GetByIdAsync(id);
if (existingUser is null)
return Results.NotFound();
user.Id = id;
await userRepository.UpdateAsync(user);
return Results.Ok(user);
});
app.MapDelete("/users/{id:int}", async (int id, IUserRepository userRepository) =>
{
var user = await userRepository.GetByIdAsync(id);
if (user is null)
return Results.NotFound();
await userRepository.DeleteAsync(id);
return Results.NoContent();
});
// New endpoint that uses the FUNCTION
app.MapGet("/users/domain/{domain}", async (string domain, IUserRepository userRepository) =>
await userRepository.GetByDomainAsync(domain));
// New endpoint that uses the STORED PROCEDURE
app.MapDelete("/users/domain/{domain}", async (string domain, IUserRepository userRepository) =>
{
await userRepository.DeleteByDomainAsync(domain);
return Results.NoContent();
});
app.Run();
Finally, we define the Unit Test.
Since we mock the IUserRepository interface, the tests are similar to the previous post (we are testing the contract, not the implementation) and we add two tests for the new methods:
[USERREPOSITORYTESTS.CS]
using Moq;
using Xunit;
namespace TestPostgreSQL.UnitTest;
public class UserRepositoryTests
{
private readonly Mock<IUserRepository> _mockRepo = new();
[Fact]
public async Task GetAllAsync_ShouldReturnAllUsers()
{
// Arrange
var users = new List<User>
{
new User { Id = 1, Username = "user1", Password = "pass1", Email = "user1@example.com" },
new User { Id = 2, Username = "user2", Password = "pass2", Email = "user2@example.com" }
};
_mockRepo.Setup(repo => repo.GetAllAsync()).ReturnsAsync(users);
// Act
var result = await _mockRepo.Object.GetAllAsync();
// Assert
Assert.Equal(2, result.Count());
Assert.Equal("user1", result.First().Username);
}
[Fact]
public async Task GetByIdAsync_ShouldReturnCorrectUser()
{
// Arrange
var user = new User { Id = 1, Username = "user1", Password = "pass1", Email = "user1@example.com" };
_mockRepo.Setup(repo => repo.GetByIdAsync(1)).ReturnsAsync(user);
// Act
var result = await _mockRepo.Object.GetByIdAsync(1);
// Assert
Assert.NotNull(result);
Assert.Equal("user1", result.Username);
}
[Fact]
public async Task GetByIdAsync_ShouldReturnNullIfUserNotFound()
{
// Arrange
_mockRepo.Setup(repo => repo.GetByIdAsync(It.IsAny<int>())).ReturnsAsync((User?)null);
// Act
var result = await _mockRepo.Object.GetByIdAsync(99);
// Assert
Assert.Null(result);
}
[Fact]
public async Task AddAsync_ShouldCallRepositoryAdd()
{
// Arrange
var user = new User { Username = "user1", Password = "pass1", Email = "user1@example.com" };
// Act
await _mockRepo.Object.AddAsync(user);
// Assert
_mockRepo.Verify(repo => repo.AddAsync(user), Times.Once);
}
[Fact]
public async Task UpdateAsync_ShouldCallRepositoryUpdate()
{
// Arrange
var user = new User { Id = 1, Username = "user1", Password = "newpass", Email = "newemail@example.com" };
// Act
await _mockRepo.Object.UpdateAsync(user);
// Assert
_mockRepo.Verify(repo => repo.UpdateAsync(user), Times.Once);
}
[Fact]
public async Task DeleteAsync_ShouldCallRepositoryDelete()
{
// Arrange
var userId = 1;
// Act
await _mockRepo.Object.DeleteAsync(userId);
// Assert
_mockRepo.Verify(repo => repo.DeleteAsync(userId), Times.Once);
}
[Fact]
public async Task GetByDomainAsync_ShouldReturnOnlyUsersOfTheDomain()
{
// Arrange
var users = new List<User>
{
new User { Id = 1, Username = "user1", Password = "pass1", Email = "user1@example.com" },
new User { Id = 2, Username = "user2", Password = "pass2", Email = "user2@example.com" }
};
_mockRepo.Setup(repo => repo.GetByDomainAsync("example.com")).ReturnsAsync(users);
// Act
var result = await _mockRepo.Object.GetByDomainAsync("example.com");
// Assert
Assert.Equal(2, result.Count());
Assert.All(result, u => Assert.EndsWith("@example.com", u.Email));
}
[Fact]
public async Task DeleteByDomainAsync_ShouldCallStoredProcedure()
{
// Arrange
_mockRepo.Setup(repo => repo.DeleteByDomainAsync("example.com")).Returns(Task.CompletedTask);
// Act
await _mockRepo.Object.DeleteByDomainAsync("example.com");
// Assert
_mockRepo.Verify(repo => repo.DeleteByDomainAsync("example.com"), Times.Once);
}
}

Finally, we run the application and, using Scalar (https://localhost:/<port>/scalar/v1), we will check that everything works fine:

ADD USER


LIST USERS


GET USER BY ID


GET BY DOMAIN


DELETE BY DOMAIN



As we can see, the application behaves exactly like the one in the previous post, but now we don’t write the SQL for the CRUD operations anymore: EF Core generates and evolves the schema through the migrations and we query the data with LINQ.
Moreover, we saw that Code First and Stored Procedures can work together: with a migration, the Function and the Procedure are versioned with the rest of the schema, and from the repository we can call them using FromSqlInterpolated (for a Function that returns rows) and ExecuteSqlInterpolatedAsync with CALL (for a Procedure).