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

时间:2011-07-21 04:38:51

标签: c# .net silverlight odata

我有一个场景,其中有多个dbs具有相同的架构,客户端可以选择要查询的数据库。有没有办法在从silverlight执行oData查询时包含数据库名称,以便它可以重用相同的服务?

假设我在客户端执行此查询(见下文)(silverlight / wp7),如何针对用户首次启动应用时选择的数据库运行此查询?

私有DataServiceCollection _employees;
        private void LoadEmployees()
        {
            DataModelContainer dmc = new DataModelContainer(new Uri(“http:// localhost:63832 / DataService.svc”));
          var query =(来自dmc.Employees中的e                          其中e.StartDate == BaseDate                          选择e);
            _employees = new DataServiceCollection(dmc);
            _employees.LoadCompleted + = new EventHandler(_employees_LoadCompleted);
            _employees.LoadAsync(查询);
        }

2 个答案:

答案 0 :(得分:0)

您应该通过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

答案 1 :(得分:0)

这是我想出的:AddQueryOption将为查询字符串添加一个值,在我的例子中是我想要运行查询的数据库的键。

var query =(来自e中的dmc.Employees.AddQueryOption(“dbKey”,SelectedDB)
 其中e.StartDate == BaseDate选择e);
 _employees = new DataServiceCollection(dmc);
 _employees.LoadCompleted + = new EventHandler(_employees_LoadCompleted);
 _employees.LoadAsync(查询);
 }

在DataService类中,我重写了CreateDataSource方法并返回一个DataModelContainer,其中包含用于查询的正确连接字符串
受保护的覆盖DataModelContainer CreateDataSource()         {
            DataModelContainer dmc = new DataModelContainer(GetConnectionString());
            return dmc;
        }
私有字符串GetConnectionString()
        {
            string dbKey = HttpContext.Current.Request.Params [“dbKey”]。ToString();
            string cnnKey =“DataModelContainer”+ dbKey;
            返回ConfigurationManager.ConnectionStrings [cnnKey] .ToString();
        }

相关问题