Windows Phone本地数据库(SQLCE):12、插入数据(翻译)

这是“windows phone mango本地数据库(sqlce)”系列短片文章的第十二篇。 为了让你开始在Windows Phone Mango中使用数据库,这一系列短片文章将覆盖所有你需要知道的知识点。我将谈谈在windows phone mango本地数据库里怎么插入数据。

   插入数据到数据库是一个两个步骤的过程。首先使用InsertOnSubmit 方法添加一个对象到DataContext,然后调用DataContext的SubmitChanges 方法来将保存数据作为数据库中的行。
注释:直到SubmitChanges调用后数据才真正保存到数据库中。

1、怎么插入数据

    在开始之前,假设我们有下面两张表的数据库结构:Country和City

复制代码
 1 [Table]
 2  public class Country  3  {  4 //...  5  }  6  7  8  [Table]  9 public class City 10  { 11 //... 12 }
复制代码

DataContext如下所示:

复制代码
 1 public class CountryDataContext : DataContext
 2  {  3 public CountryDataContext(string connectionString)  4 : base(connectionString)  5  {  6  }  7  8 public Table<Country> Countries  9  { 10 get 11  { 12 return this.GetTable<Country>(); 13  } 14  } 15 16 public Table<City> Cities 17  { 18 get 19  { 20 return this.GetTable<City>(); 21  } 22  } 23 }
复制代码

   在下面的代码示例中,我们将演示这个过程,解释上面的被装箱以及插入两个新的关系对象(city和country)到数据库中。首先,我们创建一个新的country实例,然后添加到context中(使用InsertOnSubmit 方法)。接下来,我们创建一个city实例,分配到我们刚创建的country实例,然后添加到context中。最后,我们调用SubmitChanges 方法保存这些变化到数据库中。

复制代码
 1 private void AddCity()
 2  {  3 using (CountryDataContext context = new CountryDataContext(ConnectionString))  4  {  5 // create a new country instance  6 Country country = new Country();  7 country.Name = "Spain";  8 // add the new country to the context  9  context.Countries.InsertOnSubmit(country); 10 11 // create a new city instance 12 City city = new City(); 13 city.Name = "Barcelona"; 14 // assing country 15 city.Country = country; 16 // add the new city to the context 17  context.Cities.InsertOnSubmit(city); 18 19 // save changes to the database 20  context.SubmitChanges(); 21  } 22 }
复制代码

    这篇文章我谈论了在windows phone mango本地数据库插入数据。请继续关注接下来的文章。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值