Repository Patterns - Checking Null Reference

Posted by Hon Lee on July 04, 2025

I had been tasked to looked into investigating how null references can be checked generally in a repository pattern especially when it can cover as part of unit testing, and here are some very useful tips for this.

When using the Repository Pattern in C#, it's important to handle potential null references gracefully to avoid runtime exceptions. Here's how you can check for null references effectively within a repository implementation:

✅ Example: Null Check in a Repository Method

Suppose you have a repository method like this:

public class UserRepository : IUserRepository

{

    private readonly AppDbContext _context;

    public UserRepository(AppDbContext context)

    {

        _context = context ?? throw new ArgumentNullException(nameof(context));

    }

    public User GetUserById(int id)

    {

        var user = _context.Users.Find(id);

        if (user == null)

        {

            // Handle null case appropriately

            throw new KeyNotFoundException($"User with ID {id} not found.");

        }

🔍 Key Points

  1. Constructor Null Check:

    • Ensure the injected DbContext is not null using ArgumentNullException.

  2. Entity Null Check:

    • After querying the database (e.g., Find, FirstOrDefault, SingleOrDefault), check if the result is null.

  3. Return Types:

    • You can return null, throw an exception, or use a wrapper like Result<T> or Optional<T> depending on your design philosophy.

🛡️ Optional: Using TryGet Pattern

For safer access, you can use a TryGet pattern:

public bool TryGetUserById(int id, out User user)

{

    user = _context.Users.Find(id);
    return user != null;

}