Windows Phone本地数据库(SQLCE):4、[Column]attribute(翻译) (转)
这是“windows phone mango本地数据库(sqlce)”系列短片文章的第四篇。 为了让你开始在Windows Phone Mango中使用数据库,这一系列短片文章将覆盖所有你需要知道的知识点。我将谈谈在windows phone mango本地数据库时使用[Column] attribute。
首先,要说到的是,windows phone 7.1上的数据库功能是SQL Compact关于Mango的一个实现。你将使用linq to sql访问存储在数据库上的数据。
1、[Column] attribute是什么
除了关联类到表上(之前的文章有解释过),你需要指示每一个你打算关联到数据表列的字段或属性。为此,LINQ to SQL提供了[Column] attribute。
Column attribute的各种属性,你可以精确地用来自定义字段或属性与数据表列之间的映射。值得注意的一个属性是IsPrimaryKey。它告诉LINQ to SQL表中的数据表列是主键的一部分。
参考:你可以看看MSDN的文档http://msdn.microsoft.com/zh-cn/library/system.data.linq.mapping.columnattribute.aspx
只有字段和属性声明为column会被持久化,或者从数据库中检索。其他的将被认为是你的应用程序逻辑的短暂部分。
2、怎么使用[Column] attribute
注释:
1、在属性上使用逗号来分隔多个属性
2、只能在一个类中使用Column attribute标记到[table]attribute上。(这个句子实在不太会翻译,原文是The Column attribute must be used only in a class marked with the [Table] attribute.)
1 [Table]
2 public class City
3 {
4 ...
5 [Column(IsPrimaryKey = true)]
6 public int ID
7 {
8 get;
9 set;
10 }
示例1:Column是主键
1 [Column(IsPrimaryKey = true, IsDbGenerated = true)]
2 public int ID
3 {
4 get;
5 set;
6 }
注释:上面的代码片段中,除了IsPrimaryKey属性之外,我们也可以设定IsDbGenerated 属性为true。
这告诉SQLCE runtime这个列上的值应该自动增加,这在大部分时间里是有用的。如果你需要的话,你当然可以自己生成主键值。在这种情况下,你只需要将IsDbGenerated 属性设置成默认值或者false。
示例2:Column接受空值
1 [Column(CanBeNull = false)]
2 public string Name
3 {
4 get;
5 set;
6 }
这篇文章我谈了有关在windows phone mango本地数据库中使用[Column] attribute。请继续关注接下来的文章。