21

I have the following code to set up DBContext in the .Net core 2.0 console program and it's injected to the constructor of the main application class.

 IConfigurationRoot configuration = GetConfiguration(); services.AddSingleton(configuration); Conn = configuration.GetConnectionString("ConnStr1"); services.AddDbContext<MyDbContext>(o => o.UseSqlServer(Conn)); 

Now I created a xUnit test class and need to initialize the same DbContext for testing.

 context = new MyDbContext(new DbContextOptions<MyDbContext>()); 

It gets the error of the parameter connectionString cannot be null. How to set up the DbContext in test project properly?

1
  • 6
    You just need to set options for it. As example this option are used to store db in the memory: var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>(); optionsBuilder.UseInMemoryDatabase(); var context = new MyDbContext(optionsBuilder.Options); Commented Sep 14, 2017 at 21:10

3 Answers 3

14

I found a way to do it.

var dbOption = new DbContextOptionsBuilder<MyDbContext>() .UseSqlServer("....") .Options; 
Sign up to request clarification or add additional context in comments.

1 Comment

For others looking, the other solutions are slightly more complete in that they initialize the context too!
10

The George Alexandria's solutions work for me:

var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>(); optionsBuilder.UseInMemoryDatabase(); var context = new MyDbContext(optionsBuilder.Options); 

The UseInMemoryDatabase extension method is included in Microsoft.EntityFrameworkCore.InMemory

2 Comments

For those who use this more complete method, don't forget to either use 'context.dispose()' or a using bracket i.e. using (var context = new MyDbContext(optionsBuilder.Options)){ // Your code here}.
Do you have configuration using fluent API? It seems the ModelBuilder is no available for the OnModelCreating(ModelBuilder modelBuilder) beucase it is supplied with DI from ASP.Net. Is there a way to supply the ModelBuilder for the DBContext in a testing project?
3

EF 2.0 requires that all in-memory database are named, so be sure to name it like so:

var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>(); optionsBuilder.UseInMemoryDatabase("MyInMemoryDatabseName"); var context = new MyDbContext(optionsBuilder.Options); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.