Oracle
 sql >> Database >  >> RDS >> Oracle

Entity Framework e più schemi

Durante alcune ricerche su Entity Framework mi sono imbattuto nel seguente post:

http://romiller.com/2011/05/23/ef-4-1-multi-tenant-with-code-first/

Non mi dà un singolo dbContext con cui lavorare ma usa solo una singola connessione (che era il mio ragionamento dietro il non voler usare più dbContext). Dopo aver impostato il seguente codice:

public class oraDbContext : DbContext
{
    static oraDbContext() {
        Database.SetInitializer<oraDbContext>(null);
    }

    private oraDbContext(DbConnection connection, DbCompiledModel model)
        : base(connection, model, contextOwnsConnection: false) { }

    public DbSet<SomeTable1> SomeTable1 { get; set; }
    public DbSet<SomeTable2> SomeTable2 { get; set; }

    private static ConcurrentDictionary<Tuple<string, string>, DbCompiledModel> modelCache = new ConcurrentDictionary<Tuple<string, string>, DbCompiledModel>();

    public static oraDbContext Create(string schemaName, DbConnection connection) {
        var compiledModel = modelCache.GetOrAdd(
            Tuple.Create(connection.ConnectionString, schemaName),
            t =>
            {
                var builder = new DbModelBuilder();
                builder.Configurations.Add<SomeTable1>(new SomeTable1Map(schemaName));
                builder.Configurations.Add<SomeTable2>(new SomeTable2Map(schemaName));

                var model = builder.Build(connection);
                return model.Compile();
            });

        return new oraDbContext(connection, compiledModel);
    }
}

Ciò ovviamente richiede che i miei file di mappatura siano impostati in questo modo:

public class DailyDependencyTableMap : EntityTypeConfiguration<DailyDependencyTable>
{
    public SomeTableMap(string schemaName) {
        this.ToTable("SOME_TABLE_1", schemaName.ToUpper());

        //Map other properties and stuff
    }
}

Scrivere query che utilizzano più schemi è alquanto fastidioso ma, per il momento, fa ciò di cui ho bisogno:

using (var connection = new OracleConnection("a connection string")) {
    using (var schema1 = oraDbContext.Create("SCHEMA1", connection))
    using (var schema2 = oraDbContext.Create("SCHEMA2", connection)) {

        var query = ((from a in schema1.SomeTable1 select new { a.Field1 }).ToList())
             .Concat((from b in schema2.SomeTable1 select new { b.Field1 }).ToList())
    }
}