Windows Phone 7在Mogo后提供了本地数据库供应用程序使用,开发者可以使用Linq to sql操作本地数据库 1:创建数据库 Windows Phone 中本地数据库需要开发者定义继承自DataContext的类来定义数据库,如: public class TestDb:DataContext { // 定义数据库路径及名称 public const string ConnectionStr = Data Source=isos
Windows Phone 7在Mogo后提供了本地数据库供应用程序使用,开发者可以使用Linq to sql操作本地数据库
1:创建数据库
Windows Phone 中本地数据库需要开发者定义继承自DataContext的类来定义数据库,如:
public class TestDb:DataContext { //定义数据库路径及名称 public const string ConnectionStr = "Data Source=isostore:/TestDb.sdf"; public TestDb() : base(ConnectionStr) { } }
2:创建数据表
public class DBModelBase:INotifyPropertyChanging,INotifyPropertyChanged { public event PropertyChangingEventHandler PropertyChanging; public event PropertyChangedEventHandler PropertyChanged; public void DoPropertyChanging(string propertyName) { if (PropertyChanging!=null) PropertyChanging(this, new PropertyChangingEventArgs(propertyName)); } public void DoPropertyChanged(string propertyName) { if(PropertyChanged!=null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } }
[Table] //数据表 public class AppSetting:DBModelBase { private int _iD; private string canUserGeo; //数据列,主键,不可为空,自增量,AutoSync枚举 [Column(IsPrimaryKey = true, CanBeNull = false, IsDbGenerated = true, DbType = "INT NOT NULL Identity", AutoSync = AutoSync.OnInsert)] public int ID { get { return _iD; } set { DoPropertyChanging("ID"); _iD = value; DoPropertyChanged("ID"); } } /// <summary> /// 是否允许使用Geo /// </summary> [Column] public string CanUserGeo { get { return canUserGeo; } set { DoPropertyChanging("CanUserGeo"); canUserGeo = value; DoPropertyChanged("CanUserGeo"); } } }
3:数据库类中定义表
通过Table<表类名>集合将表定义加入数据库中
public class TestDb:DataContext { public const string ConnectionStr = "Data Source=isostore:/TestDb.sdf"; public Table<AppSetting> AppSettings; public SongGuoDbA() : base(ConnectionStr) { } }
4:检测数据库是否存在,若不存在就创建。并执行插入数据操作
db = new TestDb(); if (!db.DatabaseExists()) { db.CreateDatabase(); db.AppSettings.InsertOnSubmit(new AppSetting() { CanUserGeo = "F" }); db.SubmitChanges(); }
5:数据操作
var item = db.AppSettings.FirstOrDefault();
本文来自坠翼神祇的博客,原文地址:http://www.cnblogs.com/xiaolongchen/archive/2012/09/06/2673933.html