N
N
Ness2019-08-25 10:29:01
Database
Ness, 2019-08-25 10:29:01

How to get rid of "Both an existing DbConnection and a connect" error when testing an application in xUnit?

https://gist.github.com/Taifunov/5b50081e2a86a0fc6... - my dbContext
https://gist.github.com/Taifunov/dcf99ec62140e071d... - my test class
I get this error:

System.InvalidOperationException : Both an existing DbConnection and a connection string have been configured. When an existing DbConnection is used the connection string must be set on that connection.

Tell me what am I doing wrong? I understand that the error indicates the use of two connections, but I took from the Microsoft testing example from here: https://docs.microsoft.com/en-us/ef/core/miscellan...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Egorov, 2019-08-25
@Taifunov

Well, in the example https://docs.microsoft.com/en-us/ef/core/miscellan... , from which you took the code in English, but in white it is written https://docs.microsoft.com/en-us /ef/core/miscellan...
Nevertheless, you are setting up two database providers in the context.
Here we configure to use a file instance:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
  optionsBuilder.UseSqlite("Filename=dbTest.db", options =>
  {
    options.MigrationsAssembly(Assembly.GetExecutingAssembly().FullName);
  });

  if (!optionsBuilder.IsConfigured)
  {
    optionsBuilder.UseSqlite("Filename=dbTest.db");
  }

  base.OnConfiguring(optionsBuilder);
}

And in the test, we want the base to unfold in memory:
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();

var options = new DbContextOptionsBuilder<MyDbContext>()
  .UseSqlite(connection)
  .Options;

Fix the OnConfiguring method:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
  if (!optionsBuilder.IsConfigured)
  {
    optionsBuilder.UseSqlite("Filename=dbTest.db", options =>
    {
      options.MigrationsAssembly(Assembly.GetExecutingAssembly().FullName);
    });
  }

  base.OnConfiguring(optionsBuilder);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question