简体   繁体   中英

Multiple DB contexts to a single database

I am using EF in memory database to do some unit testing. I have figured out how to populate the database with some test data and to query results through the context. The problem is that I have two db contexts. One used for adding data to the table and another with views used to access data. I don't know how to create the two contexts so that they use the same database. My unit test is returning failed, because it expected 1 result but found 0.

Any suggestions?

[Fact]
public void WhenCallingA_ThenCallReturnThis()
{
    var tableOptions = new DbContextOptionsBuilder<TableContext>()
        .UseInMemoryDatabase(databaseName: "MyDatabase")
        .Options;

    var viewOptions = new DbContextOptionsBuilder<ViewContext>()
        .UseInMemoryDatabase(databaseName: "MyDatabase")
        .Options;

    using (var tableContext = new TableContext(tableOptions))
    {
        tableContext.MyTable.Add(GenerateRecord());
        tableContext.SaveChanges();
    }

    using (var viewContext = new ViewContext(viewOptions))
    {
        Assert.Equal("HelloWorld", viewContext.MyTopics.Find(12).name);
    }
}

You cannot use view's when using InMemory database. We do not have the ability to create view when using InMemory database. View's is just a result of SQL statement. View's are very specific to Database. Entity framework treats the view as just another entity.

So, when you are using InMemory database. The MyTopics view entity and MyTable entity are represented as two separate tables in the memory. Populating data into MyTable does not fetch any results when querying MyTopics .

Instead you could refactor your test this way:

[Fact]
public void WhenCallingA_ThenCallReturnThis()
{
    var tableOptions = new DbContextOptionsBuilder<TableContext>()
        .UseInMemoryDatabase(databaseName: "MyDatabase")
        .Options;

    using (var tableContext = new TableContext(tableOptions))
    {
        tableContext.MyTable.Add(GenerateRecord());
        tableContext.SaveChanges();
    }

    using (var tableContext = new TableContext(tableOptions))
    {
        Assert.Equal(1, tableContext.MyTable.Count());
    }
}

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