Database Setup for .NET Projects

Before we dive into fabulous pre-defined Unit Of Work and Repository implementations, we need to set up a database connection in our project. To do that, create a new DbContext Class which will be given to Unit Of Work and Repository classes. Here is the example DbContext that created for demonstration purposes:

public class RENDbContext: DbContext
{
    public RENDbContext(DbContextOptions options):base(options) { }
    
    public DbSet<User> Users { get; set; }
    public DbSet<Side> Sides { get; set; }
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        ConfigureUserEntities(modelBuilder);
    }
    
    private void ConfigureUserEntities(ModelBuilder builder)
    {
        builder.Entity<User>()
            .HasOne(_ => _.Side)
            .WithMany(_=>_.Users)
            .HasForeignKey(_=>_.SideId);
    }
}

In this example I used Entity Framework Code First approach which means User and Side classes are POCO Class:

In your appsettings.json file you need to set proper Connection Strings:

Then in your Program.cs, you have the register your DbContext.

circle-info

Please note that if your json level of connectionstrings are different, you need to change the GetSection("differedpath") parameter accordingly

circle-info

Please note that in this example we used Sql Server but you can change the database according to your needs!

Then in Package Manager Console execute these commands to create your migration and apply it to database:

or alternatively, you can execute following commands in terminal:

When creating the database is done you are good to go to use REN Database Access Helpers!

Last updated