Windows Phone 本地數據庫創建、獲取數據庫物理文件、數據庫引用---本地數據庫創建


Windows Phone OS 7.1,可以將關系數據存儲在駐留在應用程序獨立存儲容器的本地數據庫中。Windows Phone 應用程序使用 LINQ to SQL 執行所有數據庫操作;LINQ to SQL 用於定義數據庫架構、選擇數據,並將更改保存到駐留在獨立存儲中的基礎數據庫文件;提到LINQ to SQL,你會不會感到欣喜,It’s amazing在window phone里我們居然可以這樣來持久化數據 :),本文將帶領大家一同建立第一個windows phone本地數據庫應用--聯系人管理。

本系列包括以下:

1.數據庫創建

2.從獨立存儲中找到數據庫文件並copy到pc上

3.復用2中的數據庫(其他程序使用2中的數據庫文件或者使用2中初始的數據)

 

一、數據庫實體表創建

1.簡介:

windwo phone之前雖然不存在內置數據庫的支持功能,但是可以使用一些開源項目,它們模仿傳統的數據庫行為將數據持久保存到獨立存儲中;

   
Windows Phone7 DataBase
http://winphone7db.codeplex.com
項目實現了一個基於獨立存儲的window phone7數據庫。該數據庫由表組成,每一個表都支持任意數量的列
Wp7 sqliteClient Preview
http://sqlitewindowsphone.codeplex.com
這是sqlite數據庫引擎的window phone7實現
Perst
http://www.mcobject.com/perst
Perst是來自mcobject公司的一個商業的面向對象數據庫系統,它可以再window phone或silverlight應用程序中高效的存儲和檢索數據

現在我們來介紹mango支持的獨立存儲中的本地數據庫,而且使用linq to sql來管理和操作數據集

Linq to sql主要是通過數據上下文(DataContext)來映射我們的Model和DB table的結構,在運行時負責橋接對象(Model)和數據(Table)部分之間;數據上下文其實是數據庫對象的一種代理,在C#中我們可以簡單的通過創建一個Linq to sql數據上下文后,從服務器資源管理器中直接將DB(MS SQL)里的Table、View、Stroreed Procedure、Function直接拖到設計窗口里,當然vs會自動幫我們產生后台Model直接的關系;但是這些操作在mango 里是不支持的,因為數據庫物理文件目前微軟並沒有提供手動創建的方法;

 

IC512992

2.數據庫創建:

linq to sql中對象關系功能是根據linq to sql中的實體映射詳細信息來創建映射到對應數據上下文,所以我們需要先創建數據上下文和實體;

要創建數據上下文和數據庫實體關系,需要添加對程序集System.Data.Linq的應用,我們實體model的特性如Table、Column都來自這個程序集

2.0創建數據上下文

首先新建一個類ContactorDataContext,然后讓這個類派生自System.Data.Linq.DataContext,並重寫構造函數

   /// <summary>
/// 數據庫上下文
/// </summary>
public class ContactorDataContext : DataContext
{
public ContactorDataContext(string connectionString)
: base(connectionString)
{ }
}


2.1創建實體model

一個實體model最終會映射為一個數據庫表(必須有Table特性),實體的屬性最終會映射為對應的列(必須有對應的Column)特性;

實體類圖如下:

類圖

代碼:

View Code
    [Table]
public class Contactor : INotifyPropertyChanged, INotifyPropertyChanging
{
/// <summary>
/// Id自動增長
/// </summary>
private int _id;
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int Id
{
get
{
return _id;
}
set
{
if (_id != value)
{
NotifyPropertyChanging("Id");
_id = value;
NotifyPropertyChanged("Id");
}
}
}

/// <summary>
/// 聯系人
/// </summary>
private string _contactorName;
[Column]
public string ContactorName
{
get
{
return _contactorName;
}
set
{
if (_contactorName != value)
{
NotifyPropertyChanging("ContactorName");
_contactorName = value;
NotifyPropertyChanged("ContactorName");
}
}
}

/// <summary>
/// 聯系電話
/// </summary>
private string _phoneNum;
[Column]
public string PhoneNum
{
get
{
return _phoneNum;
}
set
{
if (_phoneNum != value)
{
NotifyPropertyChanging("PhoneNum");
_contactorName = value;
NotifyPropertyChanged("PhoneNum");
}
}
}


/// <summary>
/// 所屬組
/// </summary>
[Column]
internal int _groupId;
private EntityRef<Group> _group;
[Association(Storage = "_group", ThisKey = "_groupId", OtherKey = "Id", IsForeignKey = true)]
public Group Group
{
get { return _group.Entity; }
set
{
NotifyPropertyChanging("Group");
_group.Entity = value;

if (value != null)
{
_groupId = value.Id;
}

NotifyPropertyChanging("Group");
}
}


#region INotifyPropertyChanged Members

public event PropertyChangedEventHandler PropertyChanged;

// Used to notify the page that a data context property changed
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

#endregion

#region INotifyPropertyChanging Members

public event PropertyChangingEventHandler PropertyChanging;

// Used to notify the data context that a data context property is about to change
private void NotifyPropertyChanging(string propertyName)
{
if (PropertyChanging != null)
{
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
}

#endregion
}

[Table]
public class Group : INotifyPropertyChanged, INotifyPropertyChanging
{
/// <summary>
/// 編號,自動增長
/// </summary>
private int _id;
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int Id
{
get
{
return _id;
}
set
{
if (_id != value)
{
NotifyPropertyChanging("Id");
_id = value;
NotifyPropertyChanged("Id");
}
}
}

/// <summary>
/// 分組名稱
/// </summary>
private string _groupName;
[Column]
public string GroupName
{
get
{
return _groupName;
}
set
{
if (_groupName != value)
{
NotifyPropertyChanging("GroupName");
_groupName = value;
NotifyPropertyChanged("GroupName");
}
}
}

/// <summary>
/// 分組描述
/// </summary>
private string _desc;
[Column]
public string Desc
{
get
{
return _desc;
}
set
{
if (_desc != value)
{
NotifyPropertyChanging("Desc");
_desc = value;
NotifyPropertyChanged("Desc");
}
}
}



#region INotifyPropertyChanged Members

public event PropertyChangedEventHandler PropertyChanged;

// Used to notify the page that a data context property changed
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

#endregion

#region INotifyPropertyChanging Members

public event PropertyChangingEventHandler PropertyChanging;

// Used to notify the data context that a data context property is about to change
private void NotifyPropertyChanging(string propertyName)
{
if (PropertyChanging != null)
{
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
}

#endregion
}

 

2.2在DataContext中添加數據集

View Code
 /// <summary>
/// 數據庫上下文
/// </summary>
public class ContactorDataContext : DataContext
{
public ContactorDataContext(string connectionString)
: base(connectionString)
{ }

/// <summary>
/// 聯系人表
/// </summary>
public Table<Contactor> Contactors;

/// <summary>
/// 分組表
/// </summary>
public Table<Group> Groups;
}



3.應用啟動時初始化數據庫

在app.xaml.cs的構造函數中創建數據庫,初始化數據庫只需要創建對應DataContext,並調用CreateDatabase()方法就可以了;

 //創建數據庫
using (ContactorDataContext db = new ContactorDataContext(DBConnectionString))
{
if (db.DatabaseExists() == false)
{
// 創建數據庫
db.CreateDatabase();

//初始化數據
InitDefaultData();
}
}



為了方便管理數據庫和數據庫model的管理,我們創建對應的DBManager類,負責管理數據庫的創建,默認數據的初始化

DataBaseManager代碼:

View Code
 public class DataBaseManager
{
public readonly static string DBConnectionString = "Data Source=isostore:/MyContactor.sdf";
/// <summary>
/// 創建數據庫
/// </summary>
public static void CreateDataBase()
{
//創建數據庫
using (ContactorDataContext db = new ContactorDataContext(DBConnectionString))
{
if (db.DatabaseExists() == false)
{
// 創建數據庫
db.CreateDatabase();

//初始化數據
InitDefaultData();
}
}
}

/// <summary>
/// 初始化數據
/// </summary>
public static void InitDefaultData()
{
ContactorDataContext db = new ContactorDataContext(DBConnectionString);
//添加三個分組
db.Groups.InsertOnSubmit(new Group { GroupName = "好友" });
db.Groups.InsertOnSubmit(new Group { GroupName = "工作" });
db.Groups.InsertOnSubmit(new Group { GroupName = "家庭" });

db.SubmitChanges();
}


/// <summary>
/// 數據庫上下文
/// </summary>
private static ContactorDataContext _contactorDataContext;
public static ContactorDataContext ContactorDataContext
{
get {
if(_contactorDataContext==null)
{
_contactorDataContext = new ContactorDataContext(DBConnectionString);
}
return _contactorDataContext;
}
}
}



好了,那么我們在app.xaml.cs構造函數去調用下就ok了..

QQ截圖20120315150244

對於測試ui很簡單,我使用了Pivot,兩個PivotItem分別顯示聯系人和聯系人分組,兩個PivotItem用於添加分組和添加聯系人,項目使用mvvm,關於mvvm使用可以看我之前的mvvm

介紹; 具體代碼可以再demo里查看..

啟動程序我們可以看到已經有了好友、工作、家庭三個分組了,這是因為在創建DataBase時,我們調用了InitDefaultData()方法,這個方法會向數據庫里添加3個默認分組;

image

這就表明我們創建數據庫和向數據庫里添加數據成功;接着將pivot移到添加分組項,添加一個新的分組名稱為test,描述為test desc,點擊save后再回到分組列表

會看到我們添加的test 分組已經再列表里,當然這並不能說明我們確實保存成功了;誰知道是否真的持久化了,那我們退出該應用(一直按back就可以了)

然后再次打開應用,這時候看到分組列表:

image

我們的test在分組列表里,這才是說明之前的保存時真的持久化了;

到這里,我們已經完整的創建好了數據庫,進行了讀寫操作(關於linq to sql的增、刪、改、查方法,這里不做過多解釋)

詳情可以運行附件的demo。

Demo


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM