Add Database Connection to Installer file

This commit is contained in:
2022-06-03 11:37:35 +01:00
parent 96a2112671
commit e7c1fde35e
5 changed files with 32 additions and 13 deletions

4
.editorconfig Normal file
View File

@@ -0,0 +1,4 @@
[*.cs]
# CS8618: Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
dotnet_diagnostic.CS8618.severity = none

View File

@@ -13,8 +13,7 @@ namespace Diary.Data
{
public DbSet<Entry> Entries { get; set; }
public DiaryDBContext(DbContextOptions<DiaryDBContext> options) : base(options)
{
public DiaryDBContext(DbContextOptions<DiaryDBContext> options) : base(options){
}
protected override void OnModelCreating(ModelBuilder builder)

View File

@@ -5,6 +5,11 @@ VisualStudioVersion = 17.0.31825.309
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Diary", "Diary.csproj", "{AC078C62-6705-45A9-A00A-7EDDCF770525}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{A852FE41-7660-406A-A6F6-8EDE1F7C1586}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU

View File

@@ -0,0 +1,17 @@
using Diary.Data;
using Microsoft.EntityFrameworkCore;
namespace Diary.Installers
{
public static class DatabaseInstaller
{
public static IServiceCollection AddDatabase(this IServiceCollection services, IConfigurationRoot config)
{
return services.AddDbContext<DiaryDBContext>(opt =>
{
string connectionString = config.GetConnectionString("Diary");
opt.UseSqlServer(connectionString);
});
}
}
}

View File

@@ -1,31 +1,25 @@
using Diary.Data;
using Diary.Installers;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
var builder = WebApplication.CreateBuilder(args);
//GetConfigStuff
IConfigurationRoot? config = new ConfigurationBuilder()
IConfigurationRoot config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json",false)
.Build();
builder.Services
.AddDbContext<DiaryDBContext>(opt =>
{
string connectionString = config.GetConnectionString("Diary");
opt.UseSqlServer(connectionString);
});
builder.Services.AddDatabase(config);
// Add services to the container.
builder.Services.AddDbContext<DiaryDBContext>();
builder.Services.AddControllers();
builder.Services.AddScoped<IDiaryDBContext, DiaryDBContext>();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();