ivandrofly

.net testcontainers demo

Dec 17th, 2024
11
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.05 KB | None | 0 0
  1. using Microsoft.EntityFrameworkCore;
  2. using Testcontainers.PostgreSql;
  3.  
  4. PostgreSqlContainer postgreSqlContainer = new PostgreSqlBuilder().Build();
  5. await postgreSqlContainer.StartAsync();
  6.  
  7. Console.WriteLine(postgreSqlContainer.GetConnectionString());
  8.  
  9. await using var gameDbContext = new GameDbContext(postgreSqlContainer);
  10. await gameDbContext.Database.EnsureCreatedAsync();
  11. // await gameDbContext.Database.MigrateAsync();
  12.  
  13. foreach (var game in gameDbContext.Games)
  14. {
  15.     Console.WriteLine(game.Name);
  16. }
  17.  
  18. Console.ReadLine();
  19.  
  20. await postgreSqlContainer.DisposeAsync();
  21.  
  22. // Intro video
  23. // https://www.youtube.com/watch?v=pvhA20OiFH8&list=PLQ176FUIyIUakfrwiENilgITi1-6eRMPb&index=9&ab_channel=JetBrains
  24.  
  25. // NOTE: NOT FROM TUTORIAL
  26. public class GameDbContext : DbContext, IAsyncDisposable
  27. {
  28.     private readonly PostgreSqlContainer _postgreSqlContainer;
  29.  
  30.     public DbSet<Game> Games { get; set; }
  31.  
  32.     //
  33.     // public GameDbContext(DbContextOptions<GameDbContext> options) : base(options)
  34.     // {
  35.     // }
  36.  
  37.     public override async ValueTask DisposeAsync()
  38.     {
  39.         // return base.DisposeAsync();
  40.         await _postgreSqlContainer.DisposeAsync();
  41.     }
  42.  
  43.     public GameDbContext(PostgreSqlContainer postgreSqlContainer)
  44.     {
  45.         _postgreSqlContainer = postgreSqlContainer;
  46.     }
  47.  
  48.     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  49.     {
  50.         base.OnConfiguring(optionsBuilder);
  51.         // optionsBuilder.EnableDetailedErrors();
  52.         optionsBuilder.UseNpgsql(_postgreSqlContainer.GetConnectionString());
  53.     }
  54.  
  55.     protected override void OnModelCreating(ModelBuilder modelBuilder)
  56.     {
  57.         modelBuilder.Entity<Game>().ToTable("Games");
  58.         modelBuilder.Entity<Game>().HasKey(g => g.Id);
  59.  
  60.         // Adding seed data
  61.         modelBuilder.Entity<Game>().HasData(
  62.             new Game { Id = 1, Name = "Chess" },
  63.             new Game { Id = 2, Name = "Monopoly" }
  64.         );
  65.     }
  66. }
  67.  
  68. public class Game
  69. {
  70.     public int Id { get; set; }
  71.     public string Name { get; set; }
  72. }
Add Comment
Please, Sign In to add comment