开发者

DbContext mapping tables dynamically

If i have a dbContext who's connection string is created during a context creation and then I want to map the table names based on some of that information....how would I pass in that data to the table mappings? For instance:

private object createContext(string name, string country)
{
    DbConnectionstringbuilder conn = new DbConnectionstringbuilder();
    conn.Add("Provider", "System.Data.SqlClient");
    conn.ConnectionString = string.Format(name, "dbName_" + country + "_moreName");   
    //maybe an if/else since we will say there are more names and countries
    return new object(conn.ToString());
}

Now when you initialize the dbcontext it is something like:

publi开发者_运维技巧c class object : DbContext
{
    public object(string conn):base(conn)
    {
        DbDatabase.SetInitializer<object>(null);
    }
//insert dbset and mapping config calls here
}

Now I want my tables to map to like "table_" + country + "_endtablename"; I guess how do I get that data passed to the mapping call?

These tables are mapped to an existing database that used this format. The country is actually coming from the credentials of the logged in user and thus based on location etc. I just need to find a way to access that country code that is an internal constructor to the base class in the latter created dbcontext.


Well ... I would make a factory method on your DbContext class then implement derived DbContext classes for each country you wish to support. This will give you the ability to customize the database initializer for each country. Since all the derived, concrete DbContexts use the same abstract parent, you can just cast them as the parent and use them. In the initializer you can use the fluent mappings to set the database name and map the table names you require. The beauty of EF Code First is that it allows you to use standard OO patterns (like Factory Method) to solve problems like the one you describe.

However, I have to say, you may want to re-think your table naming scheme. The reason you are finding this hard is because it is a somewhat unusual setup. End users don't generally go mucking around making queries directly against the tables in your database because it is too hard to enforce business rules. Unless there is a technology reason you require the tables in each database to have country-coded names, I would let the technology drive your table naming schemes and let your customer drive the end user experience. I would think that country coded database names are adequate. That achieves data separation but makes the coding much simpler and it makes queries written for one database work on the others.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜