Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Microsoft.EntityFrameworkCore;
- using Testcontainers.PostgreSql;
- PostgreSqlContainer postgreSqlContainer = new PostgreSqlBuilder().Build();
- await postgreSqlContainer.StartAsync();
- Console.WriteLine(postgreSqlContainer.GetConnectionString());
- await using var gameDbContext = new GameDbContext(postgreSqlContainer);
- await gameDbContext.Database.EnsureCreatedAsync();
- // await gameDbContext.Database.MigrateAsync();
- foreach (var game in gameDbContext.Games)
- {
- Console.WriteLine(game.Name);
- }
- Console.ReadLine();
- await postgreSqlContainer.DisposeAsync();
- // Intro video
- // https://www.youtube.com/watch?v=pvhA20OiFH8&list=PLQ176FUIyIUakfrwiENilgITi1-6eRMPb&index=9&ab_channel=JetBrains
- // NOTE: NOT FROM TUTORIAL
- public class GameDbContext : DbContext, IAsyncDisposable
- {
- private readonly PostgreSqlContainer _postgreSqlContainer;
- public DbSet<Game> Games { get; set; }
- //
- // public GameDbContext(DbContextOptions<GameDbContext> options) : base(options)
- // {
- // }
- public override async ValueTask DisposeAsync()
- {
- // return base.DisposeAsync();
- await _postgreSqlContainer.DisposeAsync();
- }
- public GameDbContext(PostgreSqlContainer postgreSqlContainer)
- {
- _postgreSqlContainer = postgreSqlContainer;
- }
- protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
- {
- base.OnConfiguring(optionsBuilder);
- // optionsBuilder.EnableDetailedErrors();
- optionsBuilder.UseNpgsql(_postgreSqlContainer.GetConnectionString());
- }
- protected override void OnModelCreating(ModelBuilder modelBuilder)
- {
- modelBuilder.Entity<Game>().ToTable("Games");
- modelBuilder.Entity<Game>().HasKey(g => g.Id);
- // Adding seed data
- modelBuilder.Entity<Game>().HasData(
- new Game { Id = 1, Name = "Chess" },
- new Game { Id = 2, Name = "Monopoly" }
- );
- }
- }
- public class Game
- {
- public int Id { get; set; }
- public string Name { get; set; }
- }
Add Comment
Please, Sign In to add comment