Instantiate Npgsql.EntityFrameworkCore.PostgreSQL's DbContext directly

c# entity-framework-core npgsql

Question

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?

1
0
8/25/2019 2:50:49 PM

Accepted Answer

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);
        }
    }
}
0
8/25/2019 2:45:46 PM

Popular Answer

The standard way to do this is to simply have a constructor on your DbContext that accepts a connection string, or a parameterless constructor and perform connection string lookup internally (e.g. via Microsoft.Extension.Configuration). Using DbContextOptionsBuilder is needlessly heavy for this use.

See the EF Core docs for regular .NET Core applications, as opposed to ASP.NET applications which typically use dependency injection.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow