# 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:

```csharp
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:

```csharp
public class User
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    
    public string Name { get; set; }
    public string Surname { get; set; }
    public Side Side { get; set; }
    public int SideId { get; set; }
}

public class Side
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    public List<User> Users { get; set; }
}
```

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

```json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "Dev": "Server=MYSERVER;Database=RENTestDb;Trusted_Connection=True;TrustServerCertificate=True"
  }
}
```

Then in your Program.cs, you have the register your DbContext.&#x20;

{% hint style="info" %}
Please note that if your json level of connectionstrings are different, you need to change the GetSection("differedpath") parameter accordingly
{% endhint %}

```csharp
builder.Services.AddDbContext<RENDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetSection("ConnectionStrings:Dev").Value);
});
```

{% hint style="info" %}
Please note that in this example we used Sql Server but you can change the database according to your needs!
{% endhint %}

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

```powershell
>> Add-Migration Migration_1
>> Update-Databse -Verbose
```

or alternatively, you can execute following commands in terminal:

```powershell
>> dotnet ef migrations add Migration_1
>> dotnet ef database update
```

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