我想遵循總體設計原則,並想出了我需要幫助的情況。我的聚合根是一個Customer
對象。 Customer
對象具有Address
對象的子集合和Contact
對象的子集合。DDD聚合根子關係NHibernate映射
A Contact
可以參考Customer
集合下的Address
。 Customer
對象具有唯一的ID
,而對象Address
和Contact
具有本地ID,因此數據庫中的主鍵爲CustomerId
和AddressId
。
這裏是簡化類:
public class Customer : AggregateRoot {
public virtual int CustomerId { get; protected set; }
public virtual IList<Address> Addresses { get; protected set; }
public virtual IList<Contact> Contacts { get; protected set; }
}
public class Address : Entity {
public Address(Customer customer, int addressId) {
this.Customer = customer;
this.AddressId = addressId;
}
public virtual Customer Customer { get; protected set; }
public virtual int AddressId { get; protected set; }
}
public class Contact : Entity {
public Contact(Customer customer, int contactId) {
this.Customer = customer;
this.ContactId = contactId;
}
public virtual Customer Customer { get; protected set; }
public virtual int ContactId { get; protected set; }
public virtual Address Address { get; set; }
}
該數據庫具有類似如下表:
客戶
CustomerId int identity PK
地址
CustomerId int not null PK,FK
AddressId int not null PK
聯繫
CustomerId int not null PK,FK
ContactId int not null PK
AddressId int null FK
當我試圖映射我與功能NHibernate實體我的問題來了。由於Address
對象具有CustomerId
和AddressId
的組合鍵,因此NHibernate不會重複使用聯繫人表中的列CustomerId
。當我嘗試保存聚集時,我收到一個異常,說有更多的值比有參數。發生這種情況的原因是地址對象具有複合ID,並且不與Contact
對象共享CustomerId
列。
我可以看到解決這個問題的唯一方法是在Contact
表中添加一個AddressCustomerId
列,但現在我有一個重複的列CustomerId
和AddressCustomerId
是相同的值。反正有這種行爲嗎?
我按照自己的方式設計它的原因是因爲我可以從數據庫中查詢單個聯繫人,而無需首先加載Customer對象。地址和聯繫人是實體,應具有本地標識符。客戶可以擁有多個獨立於聯繫人的地址,並且客戶可以擁有多個獨立於該地址的聯繫人。我對DDD相當陌生,但我認爲實體可以引用聚合根內的其他實體,這意味着實體需要本地身份。 – awilinsk 2012-08-03 11:10:47