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:
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:
{
"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.
builder.Services.AddDbContext<RENDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetSection("ConnectionStrings:Dev").Value);
});
Then in Package Manager Console execute these commands to create your migration and apply it to database:
>> Add-Migration Migration_1
>> Update-Databse -Verbose
or alternatively, you can execute following commands in terminal:
>> 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!
Last updated