简体   繁体   中英

Create fresh database from Reverse-engineered EF Core DbContext

I'm developing an Asp.Net Core Web API which will be interacting with an existing database, I'm using EF Core 3 with a reverse-engineered DbContext.

As part of the development process I would like to configure integration tests using docker, which means testing against a copy of this database in a container.

I am wondering if there's a way to create a new database in the container using the schema defined by the reverse-engineered DbContext rather than keeping (an ultimately maintaining) a copy of a create script, The database would be created at the start of the integration tests and eventually destroyed when the container is dropped

The EnsureCreated solution that @ErikEJ suggested in a comment did the trick.

Now in my OneTimeSetup method in my Nunit test class, the database is created in the docker image:

[TestFixture]
class TestClass
{
    [OneTimeSetup]
    public async Task Setup()
    {
        var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
        optionsBuilder.UseMySql("connectionString");

        await using var dbContext = new MyDbContext(optionsBuilder.Options);

        await dbContext.Database.EnsureCreatedAsync()
    }

    //...Tests
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM