Search code examples
c#entity-framework-corenpgsql

Instantiate Npgsql.EntityFrameworkCore.PostgreSQL's DbContext directly


I have created an EF Core DbContext using Npgsql.EntityFrameworkCore.PostgreSQL. I would like to instantiate this DbContext inside a test case in a unit test project. Not to create an actual unit test, but to experiment manipulating a postgresql database using this DbContext.

Since this is not an ASP.NET Core project, there is no dependency injection nor AddEntityFrameworkNpgsql / AddDbContext extension methods.

I have checked the documentation, couldn't find an example to do so.

So, how do I instantiate this DbContext directly?


Solution

  • Turned out the UseNpgsql extension method can be used here:

    using Xunit;
    using Microsoft.EntityFrameworkCore;
    using System.Linq;
    
    namespace MyTestProject
    {
        public class DbContextTest
        {
            [Fact]
            public void ActualQuery()
            {
                var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>()
                    .UseNpgsql("Host=mypgsvr;Database=mydb;Username=myusr;Password=mypass");
                var SUT = new MyDbContext(optionsBuilder.Options);
    
                var firstRow = SUT.mytable.First();
    
                Assert.NotNull(firstRow);
            }
        }
    }