Skip to content

Generating multiple database contexts in a single go

Simon Hughes edited this page Jun 6, 2019 · 20 revisions

This is an Enterprise feature which is new in the not-yet-released v3.

This will read in the filter and setting requirements from a database table, and will have the ability to generate many db contexts, poco, etc all in a single go. The database is read just once, and many (can be 100's) database contexts are generated, with just the specific tables, columns and stored procs you want in each db context, each within its own namespace.

Firstly, you need to create the multi-context settings tables. Run the following SQL script on SQL Server: MultiContextSettings.sql

In that script there are examples of how to insert data into the multi-context settings tables.

Only the exact tables/columns/etc as specified in the multi-context settings tables are generated. All other tables/columns/etc are excluded.

In your <database>.tt file, include the following, and put in a connection string to the database containing the above multi-context settings tables:

Settings.GenerateSingleDbContext = false;
Settings.MultiContextSettingsConnectionString = "";
// "Data Source=(local);Initial Catalog=EfrpgTest_Settings;Integrated Security=True;";

Here is an example of a complete <database>.tt you need for multi-context generation

<#@ include file="EF.Reverse.POCO.v3.ttinclude" #>
<#
    // Multi context single files
    Settings.DatabaseType            = DatabaseType.SqlServer; // SqlCe, Plugin. Coming next: PostgreSQL, MySql, Oracle
    Settings.GeneratorType           = GeneratorType.Ef6; // GeneratorType.EfCore;
    Settings.ConnectionString        = "Data Source=(local);Initial Catalog=EfrpgTest;Integrated Security=True";
    Settings.ConnectionStringName    = "MyDbContext"; // ConnectionString key as specified in your app.config/web.config/appsettings.json
    Settings.GenerateSeparateFiles   = false;
    Settings.Namespace               = DefaultNamespace; // Override the default namespace here
    Settings.AddUnitTestingDbContext = false;

    Settings.GenerateSingleDbContext = false;
    Settings.MultiContextSettingsConnectionString = "Data Source=(local);Initial Catalog=EfrpgTest_Settings;Integrated Security=True";

    Inflector.PluralisationService = new EnglishPluralizationService();
    var outer = (GeneratedTextTransformation) this;
    var fileManagement = new FileManagementService(outer);
    var generator = GeneratorFactory.Create(fileManagement, FileManagerFactory.GetFileManagerType());
    if (generator.InitialisationOk)
    {
        generator.ReadDatabase();
        generator.GenerateCode();
    }
    fileManagement.Process();#>

Clone this wiki locally