wp 引用数据库

引用数据库(将创建好的数据库部署到其他手机上)

第一步:创建引用数据库

  1. 创建用来创建本地数据库并使用引用数据加载该数据库的帮助器应用程序。也就是创建一个含有本地数据库功能的APP,系统第一次运行的时候会自动在独立存储中创建本地数据库。
  2. 将帮助器应用程序部署到 Windows Phone 模拟器或 Windows Phone 设备。
  3. 运行用来创建本地数据库并使用引用数据加载该数据库的相应帮助器应用程序。在独立存储中创建所有本地数据库。
  4. 获取应用程序的 Product GUID,它在 WPAppManifest.xml 文件的 App 元素的 ProductID 属性中指定。当您从独立存储复制本地数据库文件时将需要该信息。
  5. 当叠接设备或模拟器仍然运行时,使用独立存储资源管理器将本地数据库复制到您的计算机。

第二步:在部署后连接到引用数据库

当通过应用程序部署本地数据库时,数据库将存储在部署后的安装文件夹中。安装文件夹为只读。主应用程序可以通过只读方式连接到该数据库,或将其复制到独立存储以进行读写操作。本节更详细地介绍了这两种选项。

从安装文件夹读
  • 当连接到安装文件夹中的引用数据库时,必须在连接字符串中使用 File Mode 属性将连接指定为只读。下面的示例演示如何建立与安装文件夹的只读连接。有关连接字符串的更多信息,请参阅 Windows Phone 本地数据库连接字符串

// Create the data context.

MyDataContext db = new MyDataContext("Data Source = 'appdata:/mydb.sdf'; File Mode = read only;");

在本示例中,在文件路径中使用 appdata 前缀来区分安装文件夹 (appdata) 中的路径和独立存储 (isostore) 中的路径。若没有前缀,则数据上下文将应用独立存储的路径。

将引用数据库复制到独立存
  • 若要将引用数据库从安装文件夹复制到独立存储,请执行基于流的复制。下面的示例显示了一个名为 MoveReferenceDatabase 的方法,该方法将名为 ReferencedDB.sdf 的本地数据库文件从安装文件夹的根目录复制到独立存储容器的根目录。

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);

}

}

}

}

}

}

posted @ 2012-07-20 11:03  书奎  阅读(347)  评论(0编辑  收藏  举报