使用oData和EF时设置数据库名称

本文关键字:数据库 设置 oData EF 使用 | 更新日期: 2023-09-27 18:03:13

我有一个场景,其中有多个具有相同模式的数据库,客户机可以选择要查询的数据库。是否有一种方法,包括数据库名称时做一个oData查询从silverlight,所以它可以重用相同的服务?

假设我有这个查询(见下文)在客户端(silverlight/wp7)上执行,我如何让这个查询对用户第一次启动应用程序时选择的数据库运行?

private DataServiceCollection _employees;
private void LoadEmployees()
{
DataModelContainer = new DataModelContainer(new Uri("http://localhost:63832/DataService.svc"));
Var query =(从dmc中查询)员工
where e.s startdate == BaseDate选择e);
_employees = new DataServiceCollection(dmc);
_employees。LoadCompleted += new eventandler (_employees_LoadCompleted);

_employees.LoadAsync(查询);}

使用oData和EF时设置数据库名称

你应该在你的配置文件中,通过connectionstrings元素来做。

,

<configuration>
<!-- Other configuration settings -->
<connectionStrings>
  <add name="Sales" 
       providerName="System.Data.SqlClient"
       connectionString= "server=myserver;database=Products;uid=<user name>;pwd=<secure password>" />
  <add name="NorthWind" 
       providerName="System.Data.SqlClient" 
       connectionString="server=.;database=NorthWind;Integrated Security=SSPI" />
</connectionStrings>

要根据来自客户机的查询字符串动态检索连接字符串,请使用ConfigurationManager类。以下链接将在这方面为您提供帮助:

http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx

www.dotnet-guide.com/configurationmanager-class.html

这是我想到的:AddQueryOption将为查询字符串添加一个值,在我的情况下,是我想要运行查询的数据库的键。

var query = (from e in dmc.Employees.)AddQueryOption("是从"SelectedDB)
where e. startdate == BaseDate select e);
_employees = new DataServiceCollection(dmc);
_employees。LoadCompleted += new eventandler (_employees_LoadCompleted);

_employees.LoadAsync(查询);}

在DataService类中,我重写了CreateDataSource方法,并返回一个带有正确的查询连接字符串的DataModelContainer
CreateDataSource(){
DataModelContainer = new DataModelContainer(GetConnectionString());
返回dmc;
}
private string GetConnectionString()
{
string dbKey = HttpContext.Current.Request.Params["dbKey"].ToString();
string cnnKey = "DataModelContainer" + dbKey;
返回ConfigurationManager.ConnectionStrings [cnnKey] .ToString ();
}