Gener4tor
Gener4tor

Reputation: 388

Fluent nHibernate: Use the same mapping files for tables with the same structure in different schemas

This is my mapping class:

class MyTableMap : ClassMap<MyTable>
{
    public MyTableMap()
    {
        Schema("mySchema");
        Id(x => x.id);
        Map(x => x.SomeString);
    }
}           

This works fine for the Table ([mySchema].[MyTable]) in my first database.

But this table ("MyTable") exists in (actually a lot of) different databases, but for any reason the schema is always named different (this I dont have any control of):

So in the Database "OtherDB" there is the Table [SomeOtherSchema].[MyTable] with the same structure as [mySchema].[MyTable] in the first db.

For obvious reasons I dont want to create a different mapping class for every database.

So: Is there a way to change the schema of the mapping class so I just have to create one mapping class (Without using a singelton!)?

Upvotes: 21

Views: 970

Answers (1)

Gener4tor
Gener4tor

Reputation: 388

It seems like I have to use the "DefaultSchema". So I used this mapping code:

class MyTableMap : ClassMap<MyTable>
{
    public MyTableMap()
    {
        Id(x => x.id);
        Map(x => x.SomeString);
    }
}           

When I build the sessionFactory I have to set the DefaultSchema:

var configure = Fluently.Configure();
var dbConfig = MsSqlConfiguration.MsSql2012.ConnectionString("Data Source=" + dataSource +
                                                            ";Initial Catalog=" + database +
                                                            ";Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");

//Here I can set the default schema used by my mappings
var dbConfigWithSchema = dbConfig.DefaultSchema(database);  
var fluentDb = configure.Database(dbConfigWithSchema);

var fluentMap = fluentDb.Mappings(mappings);
return fluentMap.BuildSessionFactory();

Upvotes: 19

Related Questions