1

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?

2 Answers 2

2

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

Wow the man himself! :) BTW thanks for Npgsql. I'd rather not change the DbContext's constructor because I do use it in an asp.net core app with dependency injection.
Thanks for the kind words :) It should be fine to have both constructors - one for ASP.NET and one for testing - but it's also fine to build your options as you've proposed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.