How to use the EfSchemaCompare feature - JonPSmith/EfCore.TestSupport GitHub Wiki

Here is a example of using the EfSchemaCompare feature

[Fact]
public void CompareViaContext()
{
    //SETUP
    using (var context = new BookContext(_options))
    {
        var comparer = new CompareEfSql();

        //ATTEMPT
        //This will compare EF Core model of the database with the database that the context's connection points to
        var hasErrors = comparer.CompareEfWithDb(context); 

        //VERIFY
        //The CompareEfWithDb method returns true if there were errors. 
        //The comparer.GetAllErrors property returns a string, with each error on a separate line
        hasErrors.ShouldBeFalse(comparer.GetAllErrors);
    }
}

Different parameters to the CompareEfWithDb method

  1. The CompareEfWithDb method can take multiple DbContexts, known as bounded contexts (see chapter 10, section 10.6 in my book). You can add as many contexts and they are compared to one database.
  2. You can also provide a string that points to the database as the first parameter. It can have two forms:
    • It will use the string as a connection string name in the test's appsetting.json file.
    • If no connection string is found in the appsetting.json file it assumes it is a connection string.

See below for an example of both of of these options:

[Fact]
public void CompareBookThenOrderAgainstBookOrderDatabaseViaAppSettings()
{
    //SETUP
    //... I have left out how the options are created
    //This is the name of a connection string in the appsetting.json file in your test project
    const string connectionStringName = "BookOrderConnection";
    using (var context1 = new BookContext(options1))
    using (var context2 = new OrderContext(options2))
    {
        var comparer = new CompareEfSql();

        //ATTEMPT
        //Its starts with the connection string/name  and then you can have as many contexts as you like
        var hasErrors = comparer.CompareEfWithDb(connectionStringName, context1, context2);

        //VERIFY
        hasErrors.ShouldBeFalse(comparer.GetAllErrors);
    }
}

Using with database provider not installed in EfCore.TestSupport library

The EfCore.TestSupport library only contains the SqlServer and Sqlite database providers. I did that because the other databases have multiple database providers. But if you want to run the compare with a specific database provider you can do that using the version

[Fact]
public void CompareViaType()
{
    //SETUP
    using (var context = new BookContext(_options))
    {
        var comparer = new CompareEfSql();

        //ATTEMPT
        //This will use the database provider design time type you gave to get the database information
        var hasErrors = comparer.CompareEfWithDb<SqlServerDesignTimeServices>(context);

        //VERIFY
        hasErrors.ShouldBeFalse(comparer.GetAllErrors);
    }
}