文章目錄
引用資料庫(將建立好的資料庫部署到其他手機上)第一步:建立引用資料庫
- 建立用來建立本機資料庫並使用引用資料載入該資料庫的協助器應用程式。也就是建立一個含有本機資料庫功能的APP,系統第一次啟動並執行時候會自動在隔離儲存區 (Isolated Storage)中建立本機資料庫。
- 將協助器應用程式部署到 Windows Phone 模擬器或 Windows Phone 裝置。
- 運行用來建立本機資料庫並使用引用資料載入該資料庫的相應協助器應用程式。在隔離儲存區 (Isolated Storage)中建立所有本機資料庫。
- 擷取應用程式的 Product GUID,它在 WPAppManifest.xml 檔案的 App 元素的 ProductID 屬性中指定。當您從隔離儲存區 (Isolated Storage)複製本機資料庫檔案時將需要該資訊。
- 當疊接裝置或模擬器仍然運行時,使用隔離儲存區 (Isolated Storage)資源管理員將本機資料庫複製到您的電腦。
第二步:在部署後串連到引用資料庫
當通過應用程式部署本機資料庫時,資料庫將儲存在部署後的安裝資料夾中。安裝資料夾為唯讀。主應用程式可以通過唯讀方式串連到該資料庫,或將其複製到隔離儲存區 (Isolated Storage)以進行讀寫操作。本節更詳細地介紹了這兩種選項。
從安裝資料夾讀
取
- 當串連到安裝資料夾中的引用資料庫時,必須在連接字串中使用 File Mode 屬性將串連指定為唯讀。下面的樣本示範如何建立與安裝資料夾的唯讀串連。有關連接字串的更多資訊,請參閱 Windows Phone 本機資料庫連接字串。
// Create the data context.
MyDataContext db = new MyDataContext("Data Source = 'appdata:/mydb.sdf'; File Mode = read only;");
在本樣本中,在檔案路徑中使用 appdata 首碼來區分安裝資料夾 (appdata) 中的路徑和隔離儲存區 (Isolated Storage) (isostore) 中的路徑。若沒有首碼,則資料內容將應用隔離儲存區 (Isolated Storage)的路徑。
將引用資料庫複寫到獨立存
儲
- 若要將引用資料庫從安裝資料夾複製到隔離儲存區 (Isolated Storage),請執行基於流的複製。下面的樣本顯示了一個名為 MoveReferenceDatabase 的方法,該方法將名為 ReferencedDB.sdf 的本機資料庫檔案從安裝資料夾的根目錄複製到隔離儲存區 (Isolated Storage)容器的根目錄。
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
namespace PrimaryApplication
{
public class DataHelper
{
public static void MoveReferenceDatabase()
{
// Obtain the virtual store for the application.
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
// Create a stream for the file in the installation folder.
using (Stream input = Application.GetResourceStream(new Uri("ReferenceDB.sdf", UriKind.Relative)).Stream)
{
// Create a stream for the new file in isolated storage.
using (IsolatedStorageFileStream output = iso.CreateFile("ReferenceDB.sdf"))
{
// Initialize the buffer.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the file from the installation folder to isolated storage.
while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
output.Write(readBuffer, 0, bytesRead);
}
}
}
}
}
}