我想遵循总体设计原则,并想出了我需要帮助的情况。我的聚合根是一个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