🗃️ automatically add data to db when running backend

Co-authored-by: Sindre Kjelsrud <kjelsrudsindre@gmail.com>
This commit is contained in:
haraldnilsen 2023-09-18 15:23:20 +02:00
parent 3392bb55b2
commit 0fdc0e6af5
3 changed files with 40 additions and 1 deletions

View file

@ -1,10 +1,12 @@
#nullable disable
using Microsoft.EntityFrameworkCore;
using CsvHelper.Configuration;
using System.Globalization;
namespace backend;
[PrimaryKey(nameof(Id))]
// [PrimaryKey(nameof(Id))]
public class MovieDB
{
public int Id { get; set; }
@ -18,4 +20,14 @@ public class MovieDB
public string Type { get; set; }
public string Poster { get; set; }
}
public class MovieDBMap : ClassMap<MovieDB>
{
public MovieDBMap()
{
AutoMap(CultureInfo.InvariantCulture);
Map(m => m.Id).Ignore();
}
}

View file

@ -1,4 +1,10 @@
using Microsoft.EntityFrameworkCore;
using System.Globalization;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using CsvHelper;
using backend;
var builder = WebApplication.CreateBuilder(args);
@ -14,6 +20,26 @@ var configuration = builder.Configuration;
builder.Services.AddDbContext<MovieDbContext>(options =>
options.UseNpgsql(configuration.GetConnectionString("DefaultConnection")));
var services = builder.Services.BuildServiceProvider();
using (var scope = services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<MovieDbContext>();
context.Database.EnsureCreated();
// Check if movies are already inserted to avoid duplicate insertion
if (!context.Movies.Any())
{
using (var reader = new StreamReader("public/DbMockData.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Context.RegisterClassMap<MovieDBMap>();
var records = csv.GetRecords<MovieDB>().ToList();
context.Movies.AddRange(records);
context.SaveChanges();
}
}
}
var app = builder.Build();
// Configure the HTTP request pipeline.

View file

@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CsvHelper" Version="30.0.1" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.11">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>