簡體   English   中英

使用 oData 和 EF 時設置數據庫名稱

[英]Set the database name when using oData and EF

我有一個場景,其中有多個具有相同架構的數據庫,客戶端可以選擇要查詢的數據庫。 從 silverlight 進行 oData 查詢時,有沒有辦法包含數據庫名稱,以便它可以重用相同的服務?

假設我在客戶端(silverlight/wp7)上執行了這個查詢(見下文),我如何讓這個查詢針對用戶第一次啟動應用程序時選擇的數據庫運行?

私有 DataServiceCollection _employees;
私人無效LoadEmployees()
{
DataModelContainer dmc = new DataModelContainer(new Uri("http://localhost:63832/DataService.svc"));
var query = (來自 dmc.Employees 中的 e
其中 e.StartDate == BaseDate select e);
_employees = new DataServiceCollection(dmc);
_employees.LoadCompleted += new EventHandler(_employees_LoadCompleted);
_employees.LoadAsync(查詢);
}

您應該通過 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 class。 以下鏈接將在這方面為您提供幫助:

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("dbKey", SelectedDB)
其中 e.StartDate == BaseDate select e);
_employees = new DataServiceCollection(dmc);
_employees.LoadCompleted += new EventHandler(_employees_LoadCompleted);
_employees.LoadAsync(查詢);
}

在 DataService class 中,我重寫了 CreateDataSource 方法並返回一個 DataModelContainer 以及查詢的正確連接字符串
受保護的覆蓋 DataModelContainer CreateDataSource() {
DataModelContainer dmc = new DataModelContainer(GetConnectionString());
返回dmc;
}
私有字符串 GetConnectionString()
{
字符串 dbKey = HttpContext.Current.Request.Params["dbKey"].ToString();
字符串 cnnKey = "DataModelContainer" + dbKey;
返回 ConfigurationManager.ConnectionStrings[cnnKey].ToString();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM