Note Onion - 3 - Infrastructure - NotesDbContext

Here is the source code for NotesDbContext.cs file it is placed in the root directory of the Note.Infrastructure project.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Note.Domain.Entities;

namespace Note.Infrastructure.Data
{
public class NoteDataContext : DbContext
{
// sample from
// https://jasonwatmore.com/post/2022/03/18/net-6-connect-to-sql-server-with-entity-framework-core
//
protected readonly IConfiguration Configuration;

public DbSet<NoteTypeEntity> NoteTypes { get; set; }
public DbSet<NoteEntity> Notes { get; set; }

public NoteDataContext(IConfiguration configuration)
{
Configuration = configuration;
}

protected override void OnConfiguring(DbContextOptionsBuilder options)
{
// connect to sql server with connection string from app settings
options.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddDebug()))
.UseSqlServer(Configuration.GetConnectionString("NoteConnectionString")
, builder =>
{
builder.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null);
})
.EnableSensitiveDataLogging();
}


protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//this is fluentAPI - used instead of Data Annotation in the note entity
modelBuilder.Entity<NoteEntity>()
.HasOne<NoteTypeEntity>(pae => pae.NoteTypeEntity)
.WithMany(pae => pae.Notes) // pae.NoteEntity)
.HasForeignKey(p => p.NoteTypeId)
;
}

}

}