Windows Phone本地数据库(SQLCE):5、[Association]attribute(翻译)(转)
时间:2022-03-10 17:57
这是“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 是什么
- 一对一:在关联的两端使用包含属性的EntitySet<TEntity>类型表示这种关系。
- 多对多:在多对多关系中,链表(也叫联结表)的主键,通常形成其他两个表复合的一个外键。
2、怎么使用[Association] attribute
- OtherKey-属性的名称对应关联的另一端对象的id(获取或设置在关联的另一端上作为键值的、目标实体类的一个或多个成员)
- ThisKey-对于这种类型,属性的名字与外键相对应(获取或设置表示关联的此端上的键值的此实体类成员)
- Storage-这属性支持变量(获取或设置用来保存列中的值的私有存储字段。)
1 [Table] 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 [Table] 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 是“一对多”关联的“一”这一边的。
你也可以参考这里
这篇文章我谈了有关在windows phone mango本地数据库中使用[Association] attribute。请继续关注接下来的文章。
Windows Phone本地数据库(SQLCE):5、[Association]attribute(翻译)(转),布布扣,bubuko.com