Generic Repository Pattern in C#

Inspiration

Stay Connected for Heartfelt Updates!


Generic Repository Pattern in C#

Let’s begin with the Entity interface. The IEntity interface is a typical pattern used in software development to define a contract for entities, typically in the context of data access and persistence. It usually includes a property for the entity’s unique identifier. The Generic Type: The IEntity interface uses a generic type parameter TKey to allow flexibility in the type of the identifier (e.g., int, Guid, string). The ID property will identify each entity uniquely. Feel free to read more about the implementation at the entity framework core generic repository and Structured Query IEntity.

public interface IEntity<TKey>
{
    TKey Id { get; set; }
}

You might find the following definition of the generic repository pattern on the interwebs.

The Generic Repository pattern in C# is a design pattern that abstracts the application’s data layer, making it easier to manage data access logic across different data sources. It aims to reduce redundancy by implementing typical data operations in a single, generic repository rather than having separate repositories for each entity type.

public interface IGenericRepository<TEntity, TKey> where TEntity : class, IEntity<TKey>
{
    void Delete(TEntity entityToDelete);
    TEntity? GetFirstOrDefault(Expression<Func<TEntity, bool>> predicate);
    void Update(TEntity entityToUpdate);
    void Save();
    void Dispose();
}

The interface header has two generic types. TEntity is the domain class, and the TKey is the ID type, int, or string. Note that IEntity abstracts away the type TKey. It looks complex for the moment, but you will see benefits later.

Moving away from the Generic Repository, let’s focus on the pattern of the Unit of Work. According to Copilot:

The Unit of Work is a design pattern used in software development to manage and coordinate changes to a database. It ensures that all operations within a single business transaction are treated as a single unit, which means they either all succeed, or all fail together. This helps maintain data integrity and consistency.

Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application (9 of 10) | Microsoft Learn

public interface IUnitOfWork : IDisposable
{
    IGenericRepository<TEntity, TKey> Repository<TEntity, TKey>() where TEntity : class, IEntity<TKey>;
    void Save();
    Task<int> SaveAsync();
}

The Unit of Work will allow us later to inject it as a service for any repository. If you inspect the interface closely, you will notice it has three fields. The most vital of the three is the Repository. The method returns a domain of type repository and key. You can specify the type when using it.

Moving on to the Code First portion, we must tell Entity Framework how to build our database. To do so, we can create a “BloggingContext”.

public class BloggingContext: DbContext
{
    // Use design time factory
    public BloggingContext(DbContextOptions<BloggingContext> dbContextOptions)
    : base(dbContextOptions)
    {
    }
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}

If you inspect the code closely, you will notice that we inherited from DbContext, which allows us to manipulate the database. The DbContext will also enable us to use DbSets and CRUD methods. You can read more about DbContext Class on the Microsoft website.

Before using your Database Context with Code, you must set up migrations. Migrations allow you to evolve your database as you code and change the schema. I recommend you read up on Migrations managing schemas because it has excellent examples to help you start quickly.

At the high level, in Visual Studio, open up the Tools menu, then the NuGet Package Manager menu, followed by the Console. In the Console, you must install the following package.

Install-Package Microsoft.EntityFrameworkCore.Tools

The Microsoft.EntityFrameworkCore.Tools will allow you to make the following commands.

Add-Migration InitialCreate

Update-Database

Meanwhile, you might want to consider making a DesignTimeDbContextFactory because it aids in setting up the connection string for the database.

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<BloggingContext>
{
    public BloggingContext CreateDbContext(string[] args)
    {
        // Build configuration
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.Development.json")
            .Build();
        // Get connection string
        var connectionString = configuration.GetConnectionString("DefaultConnection");
        var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
        optionsBuilder.UseSqlServer(connectionString);
        return new BloggingContext(optionsBuilder.Options);
    }
}

I’m considering publishing the fully working example on Git with the following components.

  • Services
  • Domain
  • Interfaces
  • Repository
  • Console App with basic CRUD operations
  • Dependency Injection

Current Donation Amount

$2.41 – PayPal fees 🤑

Happiness Support unable to give me a total donation amount!

Note that the donation amount is being updated manually on my end. I have asked WordPress; see the image for details. I will list your name and last name initials. If you like the website backlink, donate $10 or more, and let me know in the comments your web address.

Donate to Goal of $666 to unlock Code First Generic Repository Pattern 🚀✨

Upon reaching the $666 Goal, I will share the code.

$3.00

  • Nicholas S 8.20.2024

2 responses to “Generic Repository Pattern in C#”

Leave a reply to bizcad Cancel reply

  1. bizcad Avatar
    bizcad

    After making the donation, the Current Donation Amount did not update. When I refresh the page with F5, The donation message refreshes to 0. Tsk Tsk!

    Liked by 1 person

    1. Vyechi Avatar

      Oh it’s manual, I’ll update shortly ☺️

      Liked by 1 person

I can be your coach in the following areas: Art, Nutrition, Knowledge Management
  • Grandpa Birthday Card 2023
  • Grandpa Birthday Card 2023
  • Grandpa Birthday Card 2023
  • Valkyrie’s of Abundence IINYC 12.8.21
  • Day Two: Write a List Afanc IINYC
  • I write because and draw zillo star wars
  • IINYC Prompt fudge 6.16.21
One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$1.00
$3.00
$5.00
$1.00
$3.00
$5.00
$12.00
$13.00
$14.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

ad art artblog artinfluence artist artjournal balance bunny character coda concept conceptartist creative writing creativity Design digitalart digital art doodle dragon draw drawing drawing plan environment everydayinspiration Featured fineart IINYC illustration imaginative illustrators know life live stream love mind painting plan rock studies see ski story thoughts time travel twitch WordPress

Give A Line Chain donate to make your mark on the line art.

Venmo Vye 3 black
Advertisements

Discover more from Vyechi | Personal Growth & Mindfulness

Subscribe now to keep reading and get access to the full archive.

Continue reading