2

如果我有一个 dbContext,它的连接字符串是在上下文创建期间创建的,然后我想根据其中的一些信息映射表名......我如何将该数据传递给表映射?例如:

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());
}

现在,当您初始化 dbcontext 时,它类似于:

public class object : DbContext
{
    public object(string conn):base(conn)
    {
        DbDatabase.SetInitializer<object>(null);
    }
//insert dbset and mapping config calls here
}

现在我希望我的表映射到喜欢“table_”+国家+“_endtablename”;我想如何将数据传递给映射调用?

这些表映射到使用此格式的现有数据库。该国家实际上来自登录用户的凭据,因此基于位置等。我只需要找到一种方法来访问该国家代码,该代码是后者创建的 dbcontext 中基类的内部构造函数。

4

1 回答 1

0

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.

于 2011-09-30T19:00:05.253 回答