您的位置:首页 > 数据库

Windows Phone本地数据库(SQLCE):5、[Association]attribute(翻译)(转)

2014-07-11 16:16 176 查看
这是“windows phone mango本地数据库(sqlce)”系列短片文章的第五篇。 为了让你开始在Windows Phone Mango中使用数据库,这一系列短片文章将覆盖所有你需要知道的知识点。 我将谈谈在windows phone mango本地数据库时使用[Association] attribute。

首先、要说到的是,windows phone 7.1上的数据库功能是SQL Compact关于Mango的一个实现。你将使用linq to sql访问存储在数据库上的数据。

1、 [Association] attribute 是什么

在LINQ to SQL中实体类之间的关联类似于在数据库中表之间的关联。
[Association] attribute用于指定在数据库中的一个属性来表示关联。例如一个外键到主键的关系。你也可以表示一对一或多对多的关系。

一对一:在关联的两端使用包含属性的EntitySet<TEntity>类型表示这种关系。

多对多:在多对多关系中,链表(也叫联结表)的主键,通常形成其他两个表复合的一个外键。

参考:你可以查看这里:http://msdn.microsoft.com/zh-cn/library/system.data.linq.mapping.associationattribute.aspx

2、怎么使用[Association] attribute

关联指定使用 [Association] attribute,这允许你在数据库映射中两个类型间配置关系。

[Association] attribute有下面几个重要属性:

OtherKey-属性的名称对应关联的另一端对象的id(获取或设置在关联的另一端上作为键值的、目标实体类的一个或多个成员)

ThisKey-对于这种类型,属性的名字与外键相对应(获取或设置表示关联的此端上的键值的此实体类成员)

Storage-这属性支持变量(获取或设置用来保存列中的值的私有存储字段。)

注释:括号内是MSDN上面的解释

一对多复合关联

示例1:



1 2 public class Country
3 {
4     ...
5
6   private EntitySet<City> citiesRef;
7
8     [Association(Name = "FK_Country_Cities", Storage = "citiesRef", ThisKey = "ID", OtherKey = "CountryID")]
9     public EntitySet<City> Cities
10     {
11         get
12         {
13             return this.citiesRef;
14         }
15     }
16 ...
17
18 }



注释:在上面的代码片段中,citiesRef 支持EntitySet<City>类型的变量,因为citiesRef 是“一对多”关联的“多”这一边的。

示例2:



1 
2 public class City 3 { 4 //... 5 6 private EntityRef<Country> countryRef = new EntityRef<Country>(); 7 8 9 [Association(Name = "FK_Country_Cities", Storage = "countryRef", ThisKey = "CountryID", OtherKey = "ID", IsForeignKey = true)] 10 public Country Country 11 { 12 get 13 { 14 return this.countryRef.Entity; 15 } 16 set 17 { 18 Country previousValue = this.countryRef.Entity; 19 if (((previousValue != value) || (this.countryRef.HasLoadedOrAssignedValue == false))) 20 { 21 if ((previousValue != null)) 22 { 23 this.countryRef.Entity = null; 24 previousValue.Cities.Remove(this); 25 } 26 this.countryRef.Entity = value; 27 if ((value != null)) 28 { 29 value.Cities.Add(this); 30 this.countryID = value.ID; 31 } 32 else 33 { 34 this.countryID = default(Nullable<int>); 35 } 36 } 37 } 38 } 39 //... 40 41 }



注释:在上面的代码片段中,countryRef 支持EntityRef<Country>类型的变量,因为citiesRef 是“一对多”关联的“一”这一边的。

你也可以参考这里http://www.windowsphonegeek.com/articles/Windows-Phone-Mango-Local-Database-mapping-and-database-operations

这篇文章我谈了有关在windows phone mango本地数据库中使用[Association] attribute。请继续关注接下来的文章。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐