0

私のプロジェクト仕様は、Entity Framework を使用した ASP.net MVC3 アプリケーションです。

問題は、顧客がデータベースを作成することです。個々のアプリケーションの個々のデータベースは私にとってはうまく機能しています。

しかし、単一のアプリケーションが必要であり、複数のデータベースを使用する必要があります。

同じことを達成する方法は?

4

1 に答える 1

0

Instead of creating your entity connections using the default constructor and web.config-driven connection string, you need to manually build the entity connection string and feed it into it on construction using one of the other constructors. There's usually one that takes a string, and another that takes an EntityConnection instance as well.

If the only thing that changes is the name of the database, then you can probably get away with a format string - where you perhaps take the one that's currently in your web.config - which will look something like this:

metadata=res://*;provider=System.Data.SqlClient;provider connection string="Data Source=[server];Initial Catalog=[db];User ID=[user];Password=[password]"

Note - [server], [db], [user] and [password] here are placeholders.

And simply replace the [db] with {0}.

Then - assuming you can derive a database name from a user you might do something like this following:

public string BaseConnectionString {
  get{
    //TODO: Get base connection string - can just bake in the constant string with
    //with the format placeholder.  A better thing would be to add it as an 
    //AppSetting in web.config
  }
}

//this now becomes you're primary way of getting a database connection for a user.
public MyEntities GetEntities(User user)
{
  var eConnectionString = GetConnectionString(user);

  return new MyEntities(eConnectionString);
}

public string GetConnectionString(User user)
{
   var dbName = get_db_name_for_user(user);
   return string.Format(BaseConnectionString, dbName);
}

This is but one way to achieve this. In an IOC environment it would be possible to hide all of this behind a simple Resolve<> call.

于 2012-06-12T08:18:14.817 に答える