使您的 WCF 服务会话基于,提供登录方法,在此方法中,您必须决定使用哪个数据库,如果 DataModel 相同或者每个客户端有不同的 DataModel,您可以更改 edmx 的 ConnectionString您必须为每个客户端创建一个 edmx 实例!
这里有一些简单的伪代码,entityID 标识了客户端
要创建 EntityConnectionString,请查看此链接
要创建基于会话的 WCF 服务,您必须像这样定义服务接口
[ServiceContract(SessionMode = SessionMode.Required)]
public interface ISampleService
{
[OperationContract]
void Login(string user, string password, int entityID);
}
并且 ServiceImplementation 应该具有这些属性,根据您的需要更改这些值
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Single, AutomaticSessionShutdown = true)]
public class SampleService : ISampleService
{
SampleEntities datacontext = null;
public void Login(string user, string password, int entityID)
{
if(CheckLoginData(user, password))
{
InitDataContext(entity_id);
}
}
private void InitDataContext(int entityID)
{
var connectionString = GetConnectionStringFromEntityID(entityID);
datacontext = new SampleEntities(connectionString);
}
private string GetConnectionStringFromEntityID(int entityID)
{
var providerName = "System.Data.SqlClient";
var serverName = "localhost";
var databaseName = GetDatabaseNameFromEntityID(entityID);
var sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.DataSource = serverName;
sqlBuilder.InitialCatalog = databaseName;
sqlBuilder.IntegratedSecurity = true;
var providerString = sqlBuilder.ToString();
var entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = providerName;
entityBuilder.ProviderConnectionString = providerString;
entityBuilder.Metadata = @"res://*/SampleDatabase.csdl|
res://*/SampleDatabase.ssdl|
res://*/SampleDatabase.msl";
return entityBuilder.ToString();
}
}