1 private void attach_Books(Book entity)
2 {
3 this.SendPropertyChanging();
4 entity.Publisher = this;
5 }
而Book.Publisher的赋值又触发事件使Book.PublisherId=Book.Publisher.PublisherID
01 public Publisher Publisher
02 {
03 get { … }
04 set
05 {
06 Publisher previousValue = this._Publisher.Entity;
07 if (((previousValue != value)
08 || (this._Publisher.HasLoadedOrAssignedValue == false)))
09 {
10 this.SendPropertyChanging();
11 if ((previousValue != null))
12 {
13 this._Publisher.Entity = null;
14 previousValue.Books.Remove(this);
15 }
16 this._Publisher.Entity = value;
17 if ((value != null))
18 {
19 value.Books.Add(this);
20 this._PublisherID = value.PublisherID;
21 }
22 else
23 {
24 this._PublisherID = default(System.Guid);
25 }
26 this.SendPropertyChanged("Publisher");
27 }
28 }
29 }
更新
下面代码示例了在更新Publisher记录时,同时更新相关的Book记录
1 Publisher publisher = context.Publishers.Where(
2 p => p.PublisherID == new Guid("ae825c5f-465d-4eb5-a2bb-cc1aeb5edb7d")).Single();
3 publisher.Name = "Updated Publisher";
4 var book = publisher.Books.First();
5 book.Title = "Updated book";
6
7 context.SubmitChanges();
这样的操作我们称之为什么?级联更新?事实上LINQ2SQL的实现里不存在所谓的“级联更新“。在生命周期内,每一个DataContext对象都维护着每一个查询获得的对象的引用,并且跟踪对象的修改,所有发生了修改的对象,在调用 DataContext.SubmitChanges的时候,都会被保存到数据库,这方面的内容在”LINQ那些事(6)“里会详细讨论。所以,在这里不是级联更新,而是Publisher和Book对象都发生了更改,所以在调用SubmitChanges都被保存了。